6

Given the following code, why doesn't (obj.foo)() receive window as this? It seems to me like the parentheses are ignored, rather than treated as an expression that evaluates to foo?

window.bar = 'window';
const obj = { bar: 'obj' };

obj.foo = function() {
  console.log(`Called through ${this.bar}`);
}

obj.foo(); // Called through obj

(obj.foo)(); // Called through obj - Why?

(0, obj.foo)(); // Called through window

(true && obj.foo)(); // Called through window
nik10110
  • 487
  • 4
  • 11

2 Answers2

2

They're not ignored, but the result of (obj.foo) is the same Reference (specification term) as the result of obj.foo (see this section in the spec). So the property accessor has the same information to work with to get the object and property and to use that object as this.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
1

Cause obj.foo evaluates to a Reference that contains obj and "foo". When you [[Call]] the reference, both obj and foo are known as part of the Reference.

Most operators (including the comma operator) evaluate the Reference to a value.

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151