Introduction to Analytic Function.prototype.bind
For a given function, create a new function of the bound object, which is the same as the function of previous functions, the This value is its first parameter, the other parameter, as the new function of the given parameters.
The role of BIND
The immediate role of BIND is to change the direction of this
Defines the function var checknumericrange = function (value) { if (typeof value!== ' number ') return false; else return value >= this.minimum && value <= this.maximum;} Define object var range = {minimum:10, maximum:20};
You will encounter a problem because the scope does not match, and Checknumricrange cannot manipulate the properties of the Range object.
So what are we supposed to do?
The answer is to modify the value of this. Modify this inside the function to a Range object so that the function can access the properties of the range.
Bind can be very well implemented.
The This value of the qualifying function is range and returns a new function var Boundchecknumericrange = checknumericrange.bind (range); Use the newly generated function. var result = Boundchecknumericrange (12); document.write (result);// True
Let's analyze and analyze what Checknumricrange.bind (range) has done?
By using the Bind method, the value of this is modified to a Range object, and a new function is returned, which is a range, but the function does not change.
Function.prototype.bind principle Analysis
The inner principle is a little bit around people,
A simplified bind code is given below.
Function.prototype.bind = function (scope) { var fn = this;//Here fn is this, which is called bind function, so it is convenient to call return function () {/ /Return is a can run function return fn.apply (scope);//using the Apply method, use the scope object to call FN, };}
A simple test case
var foo = { X:3} var bar = function () { console.log (this.x);} bar ();//undefined var boundfunc = Bar.bind (foo); b Oundfunc (); 3
Specific application 1. When listening to events, simplify the use of anonymous functions when triggering events
This is a counter for processing and saving data.
var logger = { x:0, updatecount:function () {this.x++; Console.log (this.x); }}
Usually use the following conditions to run the method Updatecount,
Add an anonymous function and then call the method Updatecount with the logger object to ensure that Updatecount can access the logger through this.
document.getElementsByTagName ("button") [0].addeventlistener ("click", Function () { logger.updatecount ();})
But now we can use bind to simplify the content.
document.getElementsByTagName ("button") [0].addeventlistener ("Click", Logger.updateCount.bind (Logger))
Function.prototype.bind