Page 167 - Node.js开发指南
P. 167
160 附录 A JavaScript 的高级特性
4. 理解 bind
尽管 bind 很优美,还是有一些令人迷惑的地方,例如下面的代码:
var someuser = {
name: 'byvoid',
func: function () {
console.log(this.name);
}
};
var foo = {
name: 'foobar'
};
func = someuser.func.bind(foo);
func(); // 输出 foobar
func2 = func.bind(someuser);
func2(); // 输出 foobar
全局函数 func 通过someuser.func.bind将this指针绑定到了foo,调用func()输
出了foobar。我们试图将func2赋值为已绑定的func重新通过bind将this指针绑定到
someuser的结果,而调用func2时却发现输出值仍为foobar,即 this 指针还是停留在 foo
对象上,这是为什么呢?要想解释这个现象,我们必须了解 bind 方法的原理。
让我们看一个 bind 方法的简化版本(不支持绑定参数表):
someuser.func.bind = function(self) {
return this.call(self);
};
假设上面函数是 someuser.func 的 bind 方法的实现,函数体内 this 指向的是
someuser.func,因为函数也是对象,所以 this.call(self) 的作用就是以 self 作为
this指针调用 someuser.func。
//将func = someuser.func.bind(foo)展开:
func = function() {
return someuser.func.call(foo);
};
//再将func2 = func.bind(someuser)展开:
func2 = function() {
return func.call(someuser);
};
从上面展开过程我们可以看出,func2 实际上是以 someuser 作为 func 的this指
针调用了 func,而 func 根本没有使用 this 指针,所以两次 bind 是没有效果的。