Junior — Middle
How is call context binding implemented in functions via bind?
sobes.tech AI
Answer from AI
The bind method in JavaScript is used to explicitly bind the call context (this) to a function. It returns a new function with the this context fixed to the passed object.
For example:
const obj = { name: 'Alice' };
function greet() {
console.log(`Hello, ${this.name}`);
}
const boundGreet = greet.bind(obj);
boundGreet(); // Outputs: Hello, Alice
Here, bind creates a new function boundGreet, where this will always refer to obj, regardless of how and where it is called. This is useful when you need to preserve the context, for example, when passing a function as a callback.