Method Binding and Context
You'll learn why class methods lose their this reference when passed as callbacks, and what "binding" means.
When you pass a class method as a callback (to setTimeout, an event listener, or another function), JavaScript doesn't automatically remember which object the method belongs to. The method gets "detached" from its instance, and this becomes undefined (in strict mode, which classes always use) or points to the wrong object.
Why This Happens
Think of a method like a recipe card. When the recipe is sitting in your cookbook (the class instance), it knows where all the ingredients (properties) are. But if you tear out that recipe card and hand it to someone else (pass it as a callback), the card itself doesn't carry the kitchen with it—it loses access to "your" ingredients.
class Timer {
constructor(name) {
this.name = name;
}
start() {
console.log(`${this.name} started`);
}
}
const timer = new Timer('MyTimer');
timer.start(); // Works: "MyTimer started"
setTimeout(timer.start, 1000); // Error! 'this' is undefined
In the setTimeout example, we passed timer.start as a standalone function. When it executes later, it has no idea what this should be.
The Solution: Binding
To fix this, you must "bind" the method to its instance, creating a version that always remembers its original this context. This is where the concept of "binding" comes in—you're creating a permanent connection between the method and the object.
Key Takeaway: Class methods lose their this context when passed as callbacks unless you explicitly preserve the connection between the method and its instance (binding, which we'll explore solutions for in upcoming lessons).