Preserving 'this' with Bind
You'll learn how to use bind() to lock a method's this context so it never gets lost, even when passed around.
When you extract a method from an object, it loses its connection to that object—this becomes undefined or points to the wrong thing. You've already learned that bind() can explicitly set this, but its most practical use is preserving the original context when you know a method will be called later in a different context.
The Problem in Real Scenarios
Methods often get passed as callbacks to event handlers, timers, or array methods. When that happens, the call-site changes and this gets lost:
const user = {
name: 'Alice',
greet() {
console.log(`Hello, I'm ${this.name}`);
}
};
setTimeout(user.greet, 1000); // "Hello, I'm undefined" - 'this' is lost!
The Solution: Pre-Bind the Method
Use bind() to create a new function with this permanently locked to the object:
const user = {
name: 'Alice',
greet() {
console.log(`Hello, I'm ${this.name}`);
}
};
const boundGreet = user.greet.bind(user);
setTimeout(boundGreet, 1000); // "Hello, I'm Alice" - works!
You can also bind inline when passing the callback:
setTimeout(user.greet.bind(user), 1000);
Why This Works
bind() returns a new function that calls the original method with this hardcoded to whatever you passed. No matter where or how that new function is called, this always points to your chosen object.
Key Takeaway: Use bind() to create a bound version of a method that preserves its this context, ensuring it works correctly when passed as a callback or stored for later execution.