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 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.
The comma operator ( , ) evaluates each of its operands (from left to right) and returns the value of the last operand. This lets you create a compound expression in which multiple expressions are evaluated, with the compound expression's final value being the value of the rightmost of its member expressions.
JavaScript has allowed trailing commas in array literals since the beginning, and later added them to object literals, and more recently, to function parameters and to named imports and named exports. JSON, however, disallows trailing commas.
Execution context (EC) is defined as the environment in which the JavaScript code is executed. By environment, I mean the value of this , variables, objects, and functions JavaScript code has access to at a particular time.
When the JavaScript engine first encounters your script, it creates a global execution context and pushes it to the current execution stack. Whenever the engine finds a function invocation, it creates a new execution context for that function and pushes it to the top of the stack.
You really have a nice corner case there! My take on it:
b
as the execution context.this
to the global object, but actually it's keeping it linked. Probably just so "casual" language users do not freak out.,
operator) the this
value is lost. This is because b.c
is a Property Reference
(deep rabbit hole details in the specification, here, courtesy of T.J.Crowder). 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.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.
Really nice example!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With