Function.prototype.bind()
#The bind method is used to specify the this pointer inside the function (the scope in which it is executed), and then returns a new function. The bind method does not execute a function immediately.
var keith = { a: 1, count: function() { console.log(this.a++); } }; keith.count(); //1 keith.count(); //2 keith.count(); //3
In the above code, if this.a points to the a property inside the keith object, and if this method is assigned to another variable, an error will occur when calling.
var keith = { a: 1, count: function() { console.log(this.a++); } }; var f = keith.count; f(); //NaN
In the above code, if the count method is assigned to the f variable, then the this object no longer points to the keith object, but to the window object. And window.a defaults to undefined. After the increment operation, undefined++ is equal to NaN.
In order to solve this problem, you can use the bind method to bind this in the keith object to the keith object, or call it directly.
var f = keith.count.bind(keith); f(); //1 f(); //2 f(); //3 keith.count.bind(keith)() //1 keith.count.bind(keith)() //2 keith.count.bind(keith)() //3
Of course, this can also be bound to other objects.
var obj = { a: 100 }; var f = keith.count.bind(obj); f(); //100 f(); //101 f(); //102
Similarly, we can also pass parameters to the bind method. If the first parameter is null or undefined or this, the this object inside the function will point to the global environment; The second one is the parameter required when calling, and the form of passing parameters is the same as that of the call method.
function keith(a, b) { return a + b; } console.log(keith.apply(null,[1,4])); //5 console.log(keith.call(null,1,4)); //5 console.log(keith.bind(null, 1, 4)); //keith() console.log(keith.bind(null, 1, 4)()); //5
In the above code, you can see the difference between call, apply, and bind: The call and apply methods are executed immediately after being called. After the bind call, the original function is returned, and it needs to be called again, which is a bit like a closure
The above is the detailed content of Detailed explanation of how to use the function bind method in Javascript. For more information, please follow other related articles on the PHP Chinese website!