Home > Web Front-end > JS Tutorial > body text

Summary of the use of bind method in ECMAScript5 (ES5)_Basic knowledge

WBOY
Release: 2016-05-16 16:00:33
Original
1135 people have browsed it

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:

Copy code The code is as follows:

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:

Copy code The code is as follows:

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:

Copy code The 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:

Copy code The code is as follows:

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.
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template