0

What exactly is the parsing rule in JS that results in the following:

Let's say we have this function

getThis = function(){
  return this;
}

These all work as expected using the "previous dot" rule:

getThis(); //=> Window

obj = {getThis: getThis};
obj.getThis(); //=> obj

getThisTwo = obj.getThis;
getThisTwo(); //=> Window

However, this surprises me:

(obj.getThis)() //=> obj ...WAT

My intuition would be that it would behave exactly like the 3rd example (getThisTwo). Ie, the part in parentheses is evaluated, which returns an anonymous function, which is then invoked. My expectation then is that this would be Window, not obj.

Is this a special case, or is my understanding of how this is resolved faulty?

(Edited to make the reason for my confusion clearer)

user2864740
  • 60,010
  • 15
  • 145
  • 220
akavi
  • 87
  • 3

1 Answers1

2

Yes. The value of the this context of a call depends on the type of the function invocation.

In your case, it's a method invocation - a function that is called by a property reference. And yes, parentheses do not evaluate a property reference.

See also Nature of JS bound functions and function invocation operator and this very good answer for details.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375