I have always been vague about things related to this, such as call, apply, etc. This time I saw a written test question related to bind, so I wrote this article as a reminder.
Bind, like call and apply, can change the this pointed to by the context. The difference is that call, like apply, refers directly to the method, while bind returns a method after binding this, but the internal core is still apply.
Look directly at the example:
var obj = {
a: 1,
b: 2,
getCount: function(c, d) {
Return this.a this.b c d;
}
};
window.a = window.b = 0;
console.log(obj.getCount(3, 4)); // 10
var func = obj.getCount;
console.log(func(3, 4)); // 7
Why is this happening? Because this in the context of func is window! The existence of bind is to change this pointer to obtain the desired value:
var obj = {
a: 1,
b: 2,
getCount: function(c, d) {
Return this.a this.b c d;
}
};
window.a = window.b = 0;
var func = obj.getCount.bind(obj);
console.log(func(3, 4)); // 10
Bind is a function extension method of function. After bind, the code rebinds the this pointer (obj) inside func, but it is not compatible with ie6~8. The compatible code is as follows:
var obj = {
a: 1,
b: 2,
getCount: function(c, d) {
Return this.a this.b c d;
}
};
Function.prototype.bind = Function.prototype.bind || function(context) {
var that = this;
return function() {
// console.log(arguments); // console [3,4] if ie<6-8>
Return that.apply(context, arguments);
}
}
window.a = window.b = 0;
var func = obj.getCount.bind(obj);
console.log(func(3, 4)); // 10
In fact, in my opinion, the core of bind is to return an unexecuted method. If you use apply or call directly:
var ans = obj.getCount.apply(obj, [3, 4]);
console.log(ans); // 10
It is impossible to use the abbreviated func function constructor, so use bind to pass this pointer, and then return an unexecuted method. The implementation is quite clever.