Does the comma operator influence the execution context in Javascript?

前端 未结 2 905
抹茶落季
抹茶落季 2020-11-29 03:56
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

The fi

2条回答
  •  没有蜡笔的小新
    2020-11-29 04:25

    Refer to Indirect eval call, which gives more details about it.

     (     0        ,          b.c   )        (  )
         |____|   |_____|    |_____|
         Literal  Operator   Identifier
    
         |_________________________|
         Expression
    
      |______________________________|
      PrimaryExpression
    
      |______________________________|        |________|
      MemberExpression                        Arguments
    
      |________________________________________________|
    
      CallExpression
    

    We can use the comma operator to fashion an indirect call to b.c which will force it to execute in the global context, the value of a is 1 in the global context.

    Also the result of (b.c = b.c)() is 1

    > (b.c = b.c)()
      1
    

    Speaking in terms of ECMAScript, this is because both — comma operator (in (0, b.c) example) and = operator (in (b.c = b.c) example) perform GetValue on its operands.

    Other indirect call formats as below

    > (b.c, b.c)()
      1 
    > (1? b.c: 0)()
      1
    > (__ = b.c)()
      1
    

提交回复
热议问题