Introduction
For a given function, create a new function bound to an object. This function is the same as the previous function. The value of this is its first parameter and other parameters, as a given parameter of the new function.
Functions of bind
The most direct function of BIND is to change the point of this.
// Define the function var checknumericrange = function (value) {If (typeof value! = 'Number') return false; else return value> = This. minimum & value <= This. maximum;} // defines the object var range = {minimum: 10, maximum: 20 };
In this case, a problem occurs. Because the scope does not match, checknumricrange cannot operate the attribute of the range object.
What should we do?
The answer is to modify the value of this. Change this in the function to a range object, so that the function can access the attribute of the range.
BIND can be well implemented.
// Specify the value of this for the function as range, and return 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?
The bind method is used to change the value of this to a range object, and a new function is returned. The value of this function is range, but its function has not changed.
Function. Prototype. Bind Principle Analysis
The internal principle is a bit confusing,
Below is a simplified bind code,
Function. prototype. bind = function (scope) {var fn = This; // here FN is this, that is, the function that calls the bind, which facilitates the following call of return function () {// return a function that can run return fn. apply (scope); // use the apply method to call FN,} using the scope object ,};}
A simple test case
var foo = { x: 3} var bar = function(){ console.log(this.x);} bar(); // undefined var boundFunc = bar.bind(foo); boundFunc(); // 3
Parse function. Prototype. Bind