The bind() Method
You'll learn how to lock in a this value for a function permanently, creating a new function you can call later.
What bind() Does
While call() and apply() invoke a function immediately with a specific this value, bind() creates and returns a brand new function with this permanently set. You get a "bound" function you can save and invoke whenever you want.
Think of it like this: call() is making a phone call right now, while bind() is programming a speed-dial button you'll press later.
The Syntax
const boundFunc = originalFunc.bind(thisValue);
Basic Example
const user = {
name: 'Alice',
greet: function() {
console.log(`Hello, I'm ${this.name}`);
}
};
const greet = user.greet;
greet(); // undefined - lost context
const boundGreet = user.greet.bind(user);
boundGreet(); // "Hello, I'm Alice" - works!
Why This Matters
You often need to pass methods as callbacks to event listeners or timers. Without bind(), they lose their this context:
const counter = {
count: 0,
increment: function() {
this.count++;
console.log(this.count);
}
};
setTimeout(counter.increment, 1000); // Error or undefined
const boundIncrement = counter.increment.bind(counter);
setTimeout(boundIncrement, 1000); // Works! Logs: 1
You Can Call It Multiple Times
const boundFunc = user.greet.bind(user);
boundFunc(); // "Hello, I'm Alice"
boundFunc(); // "Hello, I'm Alice"
boundFunc(); // Still works!
Key Takeaway: bind() returns a new function with this permanently attached—perfect for callbacks, event handlers, and any situation where you need to save a method for later use without losing its context.