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

相关链接
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。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,959评论 0 23
  • 320天。忙碌的时候,又开始怀念不忙的时候。想起来在上一家的时候,工作不是很忙,每天都可以准时下班,然后带上某某去...
    黑兔子Gary阅读 323评论 0 0
  • 仰视直刺蓝灰色天的中央电视塔。说起来搞笑,这塔修在京城西边,央视那大裤衩子却修在城东。幸好如今科学发达,所...
    退休人老高阅读 416评论 0 0
  • 1974年甲寅属水(虎) 1975年乙卯属水(兔) 1976年丙辰属土(龙) 1977年丁巳属土(蛇) 1978年...
    运安阁主阅读 273评论 0 0
  • 有人说20岁是个很尴尬的年龄,比上不足比下有余,而我也正处于这么一个尴尬的年龄。也因为如此,害怕做错选择,害...
    kaisin阅读 205评论 0 0