bind - 为什么不在绑定方法 polyfill 中检查这个 instanceof fBound 呢?
问题描述
这是来自 MDN 的旧版本的bind
方法 polyfill:
if (!Function.prototype.bind) {
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;
};
}
我对this instanceof fNOP
这里感到困惑。我知道有时我们可以将 fBound 返回bind
方法称为构造函数。像这样:
const fn2 = fn1.bind()
new fn2()
所以我觉得的目的this instanceof fNOP
是帮助判断我们如何调用函数return by bind
method并做一些相对的事情。但是为什么不在this instanceof fBound
这里检查呢?如果 fBound 作为构造函数调用,那么this
一定是 fBound 的一个实例,对吧?
PS:最新版的bind polyfill已经把this instanceof fNOP
check变成了fNOP.prototype.isPrototypeOf(this)
check,不过我觉得目的是一样的。无论如何,它仍然检查fNOP
而不是fBound
,我不太明白。