逗号操作符 & (0, function)()

2017-04-01  本文已影响0人  holidayPenguin

相关链接
mdn - Comma_Operator
stackoverflow - Why does babel rewrite imported function call to (0, fn)(…)?

概述

逗号操作符 对它的每个操作对象求值(从左至右),然后返回最后一个操作对象的值。

var 语句中的逗号不是逗号操作符,因为它不是存在于一个表达式中。

下面的代码,只有最后一个表达式被返回,其他的都只是被求值。

function myFunc () {
  var x = 0;

  return (x += 1, x); // the same of return ++x;
}

console.log((1, 2)); // Returns 2 in console
console.log((a = b = 3, c = 4)); // Returns 4 in console

疑问

这么去做有什么好处吗?难道就是改变我的写法?把return ++x改成return (x +=1, x)
答案当然不是

进阶

看下面的例子

var a = {
  foo: function() {
    console.log(this === window);
  }
};

a.foo(); // Returns 'false' in console
(0, a.foo)(); // Returns 'true' in console

看到没,一个输出false,一个输出true,why?

Now, in foo method, this is equal to a (because foo is attached to a). So if you call a.foo() directly, it will log false in console.
But, if you were call (0, a.foo)(). The expression (0, a.foo) will evaluate each of its operands (from left to right) and returns the value of the last operand. In other words, (0, a.foo) is equivalent to

function() {
  console.log(this === window);
}

Since this function no longer is attached to anything, its this is the global object window. That's why it log true in console when call (0, a.foo)().

看到没,由于(0, a.foo) 相当于

function() {
  console.log(this === window);
}

且这个函数不再附加到任何东西,它this是全局对象window,所以输出的是true。

上一篇 下一篇

猜你喜欢

热点阅读