相關鏈接
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。