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?
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.