逗號操作符 & (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

看到?jīng)],一個輸出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)().

看到?jīng)],由于(0, a.foo) 相當于

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

且這個函數(shù)不再附加到任何東西,它this是全局對象window,所以輸出的是true。

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 11,011評論 0 23
  • 320天。忙碌的時候,又開始懷念不忙的時候。想起來在上一家的時候,工作不是很忙,每天都可以準時下班,然后帶上某某去...
    黑兔子Gary閱讀 360評論 0 0
  • 仰視直刺藍灰色天的中央電視塔。說起來搞笑,這塔修在京城西邊,央視那大褲衩子卻修在城東。幸好如今科學發(fā)達,所...
    退休人老高閱讀 472評論 0 0
  • 1974年甲寅屬水(虎) 1975年乙卯屬水(兔) 1976年丙辰屬土(龍) 1977年丁巳屬土(蛇) 1978年...
    運安閣主閱讀 345評論 0 0
  • 有人說20歲是個很尷尬的年齡,比上不足比下有余,而我也正處于這么一個尷尬的年齡。也因為如此,害怕做錯選擇,害...
    kaisin閱讀 221評論 0 0

友情鏈接更多精彩內(nèi)容