this is decided by how a function is CALLED, not where it's defined. There are five rules:
js
obj = {
: ,
() { .; },
};
obj.();
f = obj.;
();
f.(obj);
();
this is decided by how a function is CALLED, not where it's defined. There are five rules:
obj = {
: ,
() { .; },
};
obj.();
f = obj.;
();
f.(obj);
();
Arrow functions have no own this — they inherit it from the enclosing scope at definition time. This is why arrows are perfect for callbacks:
const obj = {
items: [1, 2],
logAll() {
// ✅ arrow inherits `this` from logAll → `this` is obj
this.items.forEach(i => console.log(this.items, i));
// ❌ a regular function here would have its own `this` (undefined) → crash
// this.items.forEach(function (i) { console.log(this.items); });
},
};
Passing a method as a callback loses its binding, because it's then called plainly:
button.addEventListener("click", obj.getX); // ❌ `this` is the button
button.addEventListener("click", () => obj.getX()); // ✅ keeps obj
button.addEventListener("click", obj.getX.bind(obj)); // ✅ also fine
Misunderstanding this is one of the most common JS bugs.
The fix is usually an arrow function or .bind() to lock the intended this.