There has been a blurring of things about this, such as call, apply, and so on. This time see A and bind the pen question, therefore remember this article for forgetting.
Bind and call, as well as apply, are the one that can change the context. The difference is that call and apply are directly referenced on the method, and bind binds this to return a method, but the inner core is still apply.
See examples directly:
| 123456789101112 |
varobj = { a: 1, b: 2, getCount: function(c, d) { returnthis.a + this.b + c + d; }};window.a = window.b = 0;console.log(obj.getCount(3, 4)); // 10varfunc = obj.getCount;console.log(func(3, 4)); // 7 |
Why is this so? Because the this in the context of Func is window! Bind exists precisely in order to change this point to get the desired value:
| 1234567891011 |
varobj = { a: 1, b: 2, getCount: function(c, d) { returnthis.a + this.b + c + d; }};window.a = window.b = 0;varfunc = obj.getCount.bind(obj);console.log(func(3, 4)); // 10 |
Bind is a function extension method, bind code later rebind the func internal this point (obj), but not compatible with ie6~8, the following code is compatible:
| 12345678910111213141516171819 |
varobj = { a: 1, b: 2, getCount: function(c, d) { returnthis.a + this.b + c + d; }};Function.prototype.bind = Function.prototype.bind || function(context) { varthat = this; return function() { // console.log(arguments); // console [3,4] if ie<6-8> returnthat.apply(context, arguments); }}window.a = window.b = 0;varfunc = obj.getCount.bind(obj);console.log(func(3, 4)); // 10 |
In fact, it seems to me that the core of BIND is to return an uncommitted method if you use apply or call directly:
| 12 |
varans = obj.getCount.apply(obj, [3, 4]);console.log(ans); // 10 |
It is not possible to construct using the shorthand Func function, so passing this point with bind and returning an execution method is quite ingenious.
Introduction to bind method in ECMAScript 5 (ES5) Memo