The bind method in ECMAScript5 of ES5 USES a summary

  • 2020-06-07 04:00:30
  • OfStack

I have been vague about this, call, apply, etc. This time I have seen an bind question, so I will write it down as a reminder.

bind and call, as well as apply1, are both context-adjustable this points. The difference is that call, like apply1, refers directly to methods, whereas bind binds this and returns a method, but the inner core is still apply.

Look directly at examples:


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 that? Because func in context this is window! bind exists precisely to change the this point to get 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 this inside func to point to (obj), but it is not compatible with ie6~8. The compatibility 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, it seems to me that 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

There is no way to construct it using the abbreviated func function, so passing this points in bind and returning an unexecuted method is a neat implementation.


Related articles: