逗号运算符是否会影响Javascript中的执行上下文? [英] Does the comma operator influence the execution context in Javascript?

查看:126
本文介绍了逗号运算符是否会影响Javascript中的执行上下文?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var a = 1;
var b = {
  a : 2,
  c : function () {
    console.log(this.a);
  }
};

b.c(); // logs 2
(b.c)(); // logs 2
(0, b.c)(); // logs 1

第一个是可以理解的,因为this指向Objectb。但为什么第二个会记录相同的结果呢?我认为this应该指向全局执行上下文。第三个,似乎逗号运算符影响执行上下文。

The first is understandable, for "this" is pointed to Object "b". But why does the second one log the same result? I thought "this" should be pointed to the global execution context. And the third one, it seems that the comma operator influences the execution context.

推荐答案

你真的有一个很好的角落案例!
我的看法:

You really have a nice corner case there! My take on it:


  • 第一个是直截了当的。只是一个标准的电话。 '。'运算符允许您调用函数设置 b 作为执行上下文。

  • 第二个是完全相同的事情: parens完全是可选的,解释器将其中的表达式视为绑定函数调用。实际上我并没有想到这一点:我认为解释器会将这个重置为全局对象,但实际上它是保持链接的。可能只是那么随意的语言用户不会惊慌失措。

  • 第三个是更标准的(至少对于那些生活在JavaScript领域的人来说):只要你的函数传递给你在表达式(在本例中为运算符)中,绑定到执行上下文的值将丢失。所以,你实际上是在传递函数本身,不再与声明对象绑定。所以当你调用时,这个将作为全局对象传入。

  • the first is straightforward. Just a standard call. The '.' operator lets you call the function setting b as the execution context.
  • the second is exactly the same thing: the parens are entirely optional and the interpreter is treating the expression inside it as a bound function call. Actually I didn't expect this: I thought the interpreter would be going to reset this to the global object, but actually it's keeping it linked. Probably just so "casual" language users do not freak out.
  • the third one is more standard (at least for those who live in JavaScript land): as soon as your function is passed on in an expression (in this case by the , operator) the this value bound to the execution context is lost. So, you are actually passing around the function itself, no more bound to the declaring object. So when you call it this is going to be passed in as the global object.

这样看:(object.function)()被简化为 object.function(),因为封闭的parens是完全可选的; (0,object.function)()被解析为(表达式产生一个函数)()这将是丢失对象绑定到,因为函数已经解除绑定。

See it this way: (object.function)() gets simplyfied into object.function(), because the enclosing parens are completely optional; (0, object.function)() is parsed as (expression yielding a function)() which is going to lose the object binding to this, because function is already unbound.

非常好的例子!

这篇关于逗号运算符是否会影响Javascript中的执行上下文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆