Intermediate LevelJavaScript & TypeScript
What are call(), apply(), and bind() and how do they change function execution context?
❓ Interview Prompt: Compare call, apply, and bind regarding execution timing, argument passing, and partial application.
These three methods explicitly set the this context when executing functions:
1. fn.call(thisArg, arg1, arg2, ...):
Invokes the function immediately with thisArg and individual arguments listed sequentially.
2. fn.apply(thisArg, [arg1, arg2, ...]):
Invokes the function immediately with thisArg and arguments passed as an array.
3. fn.bind(thisArg, arg1, arg2, ...):
Does NOT execute immediately. Returns a new bound function permanently tied to thisArg and optional pre-filled arguments (partial application).
Code Implementation Example
javascript
function introduce(greeting, punctuation) {
console.log(`${greeting}, I am ${this.name}${punctuation}`);
}
const user = { name: 'Bob' };
// 1. call: arguments passed individually
introduce.call(user, 'Hello', '!'); // "Hello, I am Bob!"
// 2. apply: arguments passed as array
introduce.apply(user, ['Hi', '.']); // "Hi, I am Bob."
// 3. bind: returns bound copy for later execution
const boundIntroduce = introduce.bind(user, 'Welcome');
boundIntroduce('!!!'); // "Welcome, I am Bob!!!"💡Immediate call/apply execution vs returned bound function with bind.
🎯 Interview Key Takeaway
call passes args individually, apply passes args as an array, and bind returns a new bound function for deferred execution.
#call#apply#bind#Intermediate
Back to all JavaScript & TypeScript Questions→