For obvious reasons, in JavaScript, the following two calls are different:
foo.bar();
var bar = foo.bar;
bar();
Namely, in the first call, this
is the foo
object. In the second, it's a reference to the global scope. However, the following example is a little less intuitive:
(foo.bar)();
I would expect it to operate the same way as the second example, but it actually operates the same as the first. That is, this
references foo
, not the global scope.
What are JavaScript's rules for deciding when to make a function call a "method call" and when to simply call the function without a particular this
?
EDIT:
As Felix Kling points out in a comment, I'm wondering why the third example doesn't use the window
context when theoretically it should simply retrieve the function and call it without the additional context. His example clarifies my question a little:
(true && foo.bar)(); // 'this' refers to the global scope