MDN上面的Function.prototype.bind中的这一句该怎么理解?
发布于 11 年前 作者 ibigbug 6113 次浏览 最后一次编辑是 8 年前
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;
  };
}

原文在这里:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

12行的this instanceof fNOP && oThis中,什么情况下bind中的this才会是fNOP的instance? 看上去好像是用来区分是不是在new fBound(对oThis参数的说明:The value is ignored if the bound function is constructed using the new operator.),但是&& oThis之后逻辑又看起来很奇怪。 这里的判断该如何理解?

1 回复

bind返回的函数在作为构造函数的时候this instanceof fNOP会是true,否则就是false。

回到顶部