逗号运算符在MDN的这个polyfill中做了什么?

时间:2014-08-15 02:16:37

标签: javascript polyfills

MDN's polyfill for Function.prototype.bind(粘贴在下面),使用逗号运算符。由于逗号运算符返回最后一个操作数,并且第一个操作数(oThis)不执行任何操作(如调用函数或进行赋值),因此它看起来毫无意义。但是我假设MDN知道它在做什么,所以:在这种情况下逗号运营商做了什么有用的技巧?

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,  // <-- what's going on here?
                 aArgs.concat(Array.prototype.slice.call(arguments)));
        };

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

    return fBound;
  };
}

要明确的是,我建议您可以像这样写fBound,并让它做同样的事情:

        fBound = function () {
          return fToBind.apply(this instanceof fNOP && oThis
                 ? this
                 : aArgs.concat(Array.prototype.slice.call(arguments)));
        };

2 个答案:

答案 0 :(得分:3)

它不是逗号运算符,它是一个逗号,它将函数调用的参数分隔为fToBind。你可以改写为:

fBound = function () {
  var args = aArgs.concat(Array.prototype.slice.call(arguments));
  if (this instanceof fNOP && oThis) {
    return fToBind.apply(this, args)
  }
  return fToBind.apply(oThis, args)
};

答案 1 :(得分:1)

它等效于以下内容(除了分配给arg1和arg2的表达式在fToBind.apply之前计算,结果存储在变量中):

var arg1 = this instanceof fNOP && oThis ? this : oThis;
var arg2 = aArgs.concat(Array.prototype.slice.call(arguments));
return fToBind.apply(arg1, arg2);

也就是说,逗号作为参数分隔符存在于apply函数调用中,并且解析/实现为逗号运算符。

相关问题