1
let o = {
  a: 123,
  b: function () {
    console.log(this, this.a);
  },
};

(o.b)()

Like this code, my understanding is that the code is like this:

const b = o.b
b() // this is pointing to window

But for (o.b)(), this keyword is pointing the o object, why is that?

ChenLee
  • 1,371
  • 3
  • 15
  • 33
  • This might help, no pun intended: https://www.w3schools.com/js/js_function_call.asp – justinw Dec 22 '21 at 03:39
  • Related, though they didn't specifically talk about the `this`: https://stackoverflow.com/questions/14320835/role-of-parentheses-in-javascript – Kaiido Dec 22 '21 at 07:07

1 Answers1

0

Putting parentheses around an object reference to a function will only change the this from the object if there's something else inside the parentheses that makes the interpreter first resolve the value inside the parentheses to something else first (for example, if you use any of the operators, or invoke a function inside the parentheses).

let o = {
  a: 123,
  b: function () {
    console.log(this === window);
  },
};

// Using comma operator now
(0, o.b)()

But if all you have is a plain method reference on an object, with nothing else inside the parentheses, the calling context doesn't change - the extra parentheses around the reference doesn't change it.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320