实际上,ES5 中内置的 Function.prototype.bind(…) 更加复杂。下面是 MDN 提供的一种
bind(…) 实现,为了方便阅读我们对代码进行了排版:
if (!Function.prototype.bind) { Function.prototype.bind = function(oThis) {
if (typeof this !== "function") { // 与 ECMAScript 5 最接近的 // 内部 IsCallable 函数
throw new TypeError(
"Function.prototype.bind - what is trying " +
"to be bound is not callable"
bar(3) 并没有像我们预计的那样把 obj1.a
); }
var aArgs = Array.prototype.slice.call( arguments, 1 ), fToBind = this,
fNOP = function(){}, fBound = function(){
return fToBind.apply( (
this instanceof fNOP &&
oThis ? this : oThis ),
aArgs.concat(
Array.prototype.slice.call( arguments )
); }
;
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP(); return fBound;
}; }
下面是 new 修改 this 的相关代码: this instanceof fNOP &&
fNOP.prototype = this.prototype; fBound.prototype = new fNOP();
我们并不会详细解释这段代码做了什么(这非常复杂并且不在我们的讨论范围之内),不 过简单来说,这段代码会判断硬绑定函数是否是被 new 调用,如果是的话就会使用新创建 的 this 替换硬绑定的 this。
那么,为什么要在 new 中使用硬绑定函数呢?直接使用普通函数不是更简单吗?
之所以要在 new 中使用硬绑定函数,主要目的是预先设置函数的一些参数,这样在使用 new 进行初始化时就可以只传入其余的参数。bind(…) 的功能之一就是可以把除了第一个 参数(第一个参数用于绑定 this)之外的其他参数都传给下层的函数(这种技术称为“部 分应用”,是“柯里化”的一种)。举例来说:
function foo(p1,p2) { this.val = p1 + p2;
}
之所以使用 null 是因为在本例中我们并不关心硬绑定的 this 是什么 // 反正使用 new 时 this 会被修改
var bar = foo.bind( null, "p1" );
var baz = new bar( "p2" ); baz.val; // p1p2