simplify the life ECMAScript 5(ES5)中bind方法简介

一直以来对和this有关的东西模糊不清,譬如call、apply等等。这次看到一个和bind有关的笔试题,故记此文以备忘。

  bind和call以及apply一样,都是可以改变上下文的this指向的。不同的是,call和apply一样,直接引用在方法上,而bind绑定this后返回一个方法,但内部核心还是apply。

  直接看例子:

1
2
3
4
5
6
7
8
9
10
11
12
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

  为何会这样?因为func在上下文中的this是window!bind的存在正是为了改变this指向获取想要的值:

1
2
3
4
5
6
7
8
9
10
11
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是function的一个函数扩展方法,bind以后代码重新绑定了func内部的this指向(obj),但是不兼容ie6~8,兼容代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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

  其实在我看来bind的核心是返回一个未执行的方法,如果直接使用apply或者call:

1
2
var ans = obj.getCount.apply(obj, [3, 4]);
console.log(ans); // 10

  无法使用简写的func函数构造,所以用bind传递this指向,再返回一个未执行的方法,实现方式相当巧妙。

  

2015-6-10补充:

  昨天看到一个bind在代码中的装逼实现。如何用setTimeout连续打印0~9?

  以前试过的朋友肯定知道,直接打印是不行的,会打印出一样的数字,这时候就要用闭包了,闭包的话有两种方式,简单实现一种如下:

复制代码
for(var i = 0; i < 10; i++) {
  ~function(i) {
    setTimeout(function() {
      console.log(i);
    }, i * 1000);
  }(i);
}
复制代码

  但是居然用bind也能实现:

for(var i = 0; i < 10; i++) {
  setTimeout(console.log.bind(console, i), i * 1000);
}

  这样为何也能实现,我也是百思不得其解,只能说不明觉厉。

  bind是和apply、call一样,是Function的扩展方法,所以应用场景是func.bind(),而传的参数形式和call一样,第一个参数是this指向,之后的参数是func的实参,fun.bind(thisArg[, arg1[, arg2[, ...]]])。

原文地址:https://www.cnblogs.com/freefish12/p/bind.html