无法理解绑定polyfill中的原型

时间:2016-11-23 12:08:54

标签: javascript bind prototypejs polyfills prototype-chain

我通过MDN阅读了polyfill的bind函数。 我无法理解为什么 fBound.prototype = new fNOP(); 是用代码写的? 我有一个链接,但无法理解作者试图传达的内容(mozilla's bind function question

这是代码:



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)));
        };

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

    return fBound;
  };
}




1 个答案:

答案 0 :(得分:0)

answer很好地解释了您的问题,因此我建议将此问题标记为重复,或者您可以在该答案中添加评论。

简而言之,fBound.prototype = new fNOP()用于解决this的优先级,即:

new绑定>显式绑定(callapplybind)>隐式绑定(var bar = obj1.foo())>默认绑定(undefined / global对象)

更多详细信息和原因:determining this

fBound.prototype = new fNOP()用于this instanceof fNOP ? this : oThis

如果this instanceof fNOP返回true,则表示thisnew创建对象,并且fBound被称为构造函数:new fBound(),因此请丢弃oThis,使用this。 (new绑定)

如果this instanceof fNOP返回false,则意味着fBound被作为普通函数调用,因此请使用oThis中传递的bind。 (显式绑定)