Problem Statement
What does the bind() method return?
Explanation
Bind creates a new function with a permanently bound this value. Unlike call and apply, bind does not execute the function immediately.
First parameter sets the this value. Additional parameters are pre-set as arguments.
The returned function can be called later, and this will always be the bound value.
Bind is useful for event handlers, callbacks, and partial application.
You can only bind this once. Calling bind again on a bound function does nothing.
Bind is essential for maintaining context in callbacks and React components.
Code Solution
SolutionRead Only
const person = {
name: 'John',
greet: function() {
console.log('Hi, I am ' + this.name);
}
};
// bind creates new function
const greetFunc = person.greet.bind(person);
// Call later, this is still person
greetFunc(); // 'Hi, I am John'
// Without bind, this is lost
const greetLost = person.greet;
greetLost(); // 'Hi, I am undefined' (this is window or undefined)
// Event handler example
const button = document.getElementById('btn');
const user = {
name: 'Alice',
handleClick: function() {
console.log(this.name + ' clicked');
}
};
// Wrong: this will be button element
// button.addEventListener('click', user.handleClick);
// Right: bind this to user
button.addEventListener('click', user.handleClick.bind(user));
// Now clicking shows 'Alice clicked'
// Partial application with bind
function multiply(a, b) {
return a * b;
}
// Pre-set first argument
const double = multiply.bind(null, 2);
console.log(double(5)); // 10 (2 * 5)
console.log(double(7)); // 14 (2 * 7)
const triple = multiply.bind(null, 3);
console.log(triple(4)); // 12 (3 * 4)
// setTimeout example
const obj = {
value: 42,
printValue: function() {
console.log(this.value);
}
};
setTimeout(obj.printValue, 1000); // undefined (lost this)
setTimeout(obj.printValue.bind(obj), 1000); // 42 (preserved this)
// Cannot rebind
const bound = greetFunc.bind({ name: 'Jane' });
bound(); // Still 'Hi, I am John' (first bind wins)