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

不得不说js的方法真是魔性,城会玩

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值