Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does JavaScript determine when to give a function call a "this" context? [duplicate]

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
like image 407
Alexis King Avatar asked Feb 23 '14 00:02

Alexis King


1 Answers

That's a tricky one and boils down to the inner workings of the ECMAScript standard. The definition of the grouping operator is:

The production PrimaryExpression : ( Expression ) is evaluated as follows:

  1. Return the result of evaluating Expression. This may be of type Reference.

With the added note:

This algorithm does not apply GetValue to the result of evaluating Expression. The principal motivation for this is so that operators such as delete and typeof may be applied to parenthesised expressions.

So this is the key: The result can be of type Reference. A Reference is an internal data type which consists of a base value and a referenced name.

For example evaluating the member expression foo.bar, results in a Reference with base value foo (the object) and the referenced name "bar" (simply a string representation of the identifier).

GetValue(ref) is the internal function which actually accesses the property of the object and returns the value of the property (the function object in this examples). Most operators call GetValue on their operands do resolve these References, but not the grouping operator.


Looking at how CallExpressions are evaluated might also give an idea of how this and References work. For example, one step is:

Let thisValue be the result of calling the ImplicitThisValue concrete method of GetBase(ref).

So, if you have a Reference value and try to call it, the value of this will be set to the base value of the Reference (foo in the above example).


Regarding my example (true && foo.bar)();: The && operator calls GetValue() on both of its operands, so the result of the grouping operator is not a Reference.

like image 145
Felix Kling Avatar answered Oct 02 '22 19:10

Felix Kling