Class Methods as Callbacks
You'll learn: Why passing class methods directly as callbacks breaks this binding and how to fix it.
The Problem: Methods Become Orphans
When you pass a class method as a callback (like to an event listener or setTimeout), you're extracting the method from its instance. Remember: the call-site determines this, not where the method was defined.
class Counter {
constructor() {
this.count = 0;
}
increment() {
this.count++;
console.log(this.count);
}
}
const myCounter = new Counter();
// Direct call works fine:
myCounter.increment(); // 1
// As a callback, 'this' is lost:
setTimeout(myCounter.increment, 1000); // TypeError: Cannot read property 'count' of undefined
The callback system calls increment() as a plain function, not as a method on myCounter. No object context means this is undefined (in strict mode).
The Fix: Preserve the Context
You've already learned two solutions:
Option 1: Use bind()
setTimeout(myCounter.increment.bind(myCounter), 1000); // Works!
Option 2: Arrow function wrapper
setTimeout(() => myCounter.increment(), 1000); // Works!
Both ensure this inside increment refers to myCounter.
Why This Matters
This pattern appears constantly: DOM event handlers, array methods, timers, and async callbacks. Forgetting to bind context is one of the most common this-related bugs in JavaScript classes.
Key Takeaway: Passing class methods as callbacks requires explicit binding (via bind() or arrow functions) because the callback system doesn't preserve the instance context—it just calls the function with no object attached.