为什么Function.prototype.bind返回一个构造函数?

时间:2014-12-07 18:20:53

标签: javascript

我正在查看Function.prototype.bind方法的polyfill。

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

任何人explain我可以为什么这样做?如果我没有使用fn运算符调用我的new,我认为这些步骤是不必要的。如果未通过新运算符调用,为什么返回的fn必须是constructor

fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();    
return fBound;

我们可以在下面执行以下操作而不是创建new constructor吗?

fBound.prototype = Object.create(this.prototype);
return fBound

1 个答案:

答案 0 :(得分:1)

你可以......如果支持Object.create

但如果您正在填充Function.prototype.bind,则可能还必须填充Object.create

Object.create的polyfill基本上是你不必要的部分:

Object.create = (function() {
    var fNOP = function() {};
    return function (prototype) {
        if (arguments.length > 1) throw Error('Second argument not supported');
        if (typeof prototype != 'object') throw TypeError('Argument must be an object');
        fNOP.prototype = prototype;
        var result = new fNOP();
        fNOP.prototype = null;
        return result;
    };
})();