MDN绑定填充如下所示。
我正在努力想出
this instanceof fNOP ? this : oThis在fToBind.apply调用中。
我没法把头绕过去。有人能帮我弄清楚吗?
Function.prototype.bindMdn = 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 ? this : oThis, aArgs.concat(Array.prototype.slice.call(arguments)));
}
;
if (this.prototype) {
// Function.prototype doesn't have a prototype property
fNOP.prototype = this.prototype;
}
fBound.prototype = new fNOP();
return fBound;
};如果在调用绑定函数时将绑定函数的实例作为目标提供,则似乎是短路,但是类型检查应该会捕捉到这一点,因此我不理解它的存在。
链接到MDN页面:
编辑:,这是一个与建议的复制不同的问题。建议的重复询问为什么需要fNOP。我完全感觉到了。
这个问题是为什么需要instanceof检查以及它提供什么功能。我在上面提出了我的短路假说,并给出了一个不完全合理的理由。
发布于 2016-07-16 15:23:15
如果您使用.bind的结果来使用new创建一个新实例
function TestClass(a,b,c,d) {
}
var TestClassBound = TestClass.bindMdn(null, 1, 2, 3);
new TestClassBound();然后this instanceof fNOP是true。
typeof this !== 'function'只是为了测试它是否在函数上被称为常规方式,而不是使用call或apply,或者确保它没有被复制到另一个对象原型。所以它只会阻止像
Function.prototype.bind.call("Not a function", 1, 2, 3);或
var testObj = {};
testObj.bind = Function.prototype.bind;
testObj.bind(1,2,3);对于函数上的每个常规bind调用,typeof this将始终是function。
因此,typeof this !== 'function'将检查调用对象bind是否真的是一个函数。
并且,在使用绑定的结果时,this instanceof fNOP在fBind中确保行为是正确的。
https://stackoverflow.com/questions/38412423
复制相似问题