从link开始,有一段代码:
Function.prototype.bind = function(oThis) {
if (typeof this !== "function") {
// closest thing possible to the ECMAScript 5
// internal IsCallable function
throw new TypeError( "Function.prototype.bind - what " +
"is trying to be bound is not callable"
);
}
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;
};
function foo(p1,p2) {
this.val = p1 + p2;
}
// using `null` here because we don't care about
// the `this` hard-binding in this scenario, and
// it will be overridden by the `new` call anyway!
var bar = foo.bind( null, "p1" );
var baz = new bar( "p2" );
console.log(baz.val); // p1p2
我在Chrome中运行这段代码。我得到了' undenfined'的输出,而不是' p1p2'的答案。列在书中
我发现,将 null 传递给bind函数是不正确的。传入 null 时,此位于代码行' this.val = p1 + p2;'等于' 窗口'而不是baz对象。
但是,如果我使用bind的内置函数,输出是正确的。 我认为这段代码会产生巨大的误解。
有人可以给我更多澄清吗?