【问题标题】:JavaScript function.prototype.bind polyfillJavaScript function.prototype.bind polyfill
【发布时间】:2016-12-28 15:23:49
【问题描述】:

为什么我们需要在这里使用 instanceOf ,在这种情况下结果将是 true ?

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
                 ? this
                 : oThis,
                 aArgs.concat(Array.prototype.slice.call(arguments)));

// 这里为什么要使用instanceOf };

    if (this.prototype) {
      // Function.prototype doesn't have a prototype property
      fNOP.prototype = this.prototype; 
    }
    fBound.prototype = new fNOP();

    return fBound;
  };
}

//哪种情况下结果为真?

【问题讨论】:

  • 我认为当您在已绑定的函数上调用 .bind() 时可能会处理它,但我尝试删除测试并且它的工作原理相同。
  • 一般它 if(this instanceof fNOP) return false 为什么使用它?看不懂

标签: javascript bind instanceof polyfills


【解决方案1】:

我认为这是下面问题的重复,只是变量在 2011 年被问到时的名称略有不同,所以很容易不注意到它:

mozilla's bind function question

查看该问题以获得完整解释(如果您同意它是您问题的答案,请投票赞成),但关键是:

它允许您将绑定函数作为构造函数调用,而无需绑定到原始对象。换句话说,如果您使用 new 调用“绑定”函数,它仍将像原始的未绑定版本一样工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-24
    相关资源
    最近更新 更多