MDN绑定polyfill中的行的说明

Ben*_*Ben 6 javascript

MDN结合填充物如下所示.

我正在努力找出目的

this instanceof fNOP ? this : oThis
Run Code Online (Sandbox Code Playgroud)

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;
};
Run Code Online (Sandbox Code Playgroud)

如果在调用绑定函数时将绑定函数的实例作为目标提供,则似乎是短路,但是类型检查应该捕获这个,所以我不理解它的存在.

链接到MDN页面:

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind

编辑:这是与建议的副本不同的问题.建议的副本询问为什么fNOP需要.我完全理解了这一点.

这个问题是为什么instanceof需要检查以及它服务的功能.我在上面提出了我的短路假设,以及为什么这个假设没有充分理由.

t.n*_*ese 5

如果您使用 a 的结果.bind创建一个新实例new

 function TestClass(a,b,c,d) {
 }

 var TestClassBound = TestClass.bindMdn(null, 1, 2, 3);

 new TestClassBound();
Run Code Online (Sandbox Code Playgroud)

然后this instanceof fNOPtrue

typeof this !== 'function'是只是为了测试,如果它被称为上的功能,而不是常规的方式与callapply或以确保它没有被复制到另一个对象的原型。所以它只会阻止类似的事情

Function.prototype.bind.call("Not a function", 1, 2, 3);
Run Code Online (Sandbox Code Playgroud)

或者

var testObj = {};
testObj.bind = Function.prototype.bind;

testObj.bind(1,2,3);
Run Code Online (Sandbox Code Playgroud)

对于bind函数的每次常规调用,typeof this将始终为function.

所以typeof this !== 'function'就是检查bind被调用的对象是否真的是一个函数。

this instanceof fNOP该内fBind确保在使用结合的结果的行为是正确的。