The this Keyword
Prerequisites: Classes and objects, Arrow functions
this refers to "the object the current method was called on" — but
unlike Python's explicit self, JavaScript sets it automatically
based on how a function is called, which is a common source of bugs.
class Counter {
count = 0;
increment() {
this.count++;
}
}
const counter = new Counter();
const fn = counter.increment;
// fn(); // would throw — "this" is lost when detached like this
const arrowFn = () => counter.increment();
arrowFn(); // works — arrow functions don't have their own "this"
Common mistakes
- Passing a class method as a callback directly (e.g. to
button.addEventListener("click", obj.method)) and losing itsthis— wrap it in an arrow function instead:() => obj.method().