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.
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) thethis
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 itthis
is going to be passed in as the global object.See it this way:
(object.function)()
gets simplyfied intoobject.function()
, because the enclosing parens are completely optional;(0, object.function)()
is parsed as(expression yielding a function)()
which is going to lose theobject
binding tothis
, because function is already unbound.Really nice example!
Refer to Indirect eval call, which gives more details about it.
We can use the comma operator to fashion an indirect call to
b.c
which will force it to execute in theglobal context
, the value ofa
is1
in theglobal context
.Also the result of
(b.c = b.c)()
is1
Other indirect call formats as below