JavaScript Intermediate
How do you use call, apply, and bind in JavaScript?
Overview
call, apply, and bind all manually set the this context of a function (explicit binding).
call
Immediately invokes the function. First argument is this, remaining arguments are passed individually.
function greet(greeting, punctuation) {
console.log(greeting + ', ' + this.name + punctuation);
}
const user = { name: 'Alice' };
greet.call(user, 'Hello', '!'); // 'Hello, Alice!'
apply
Immediately invokes the function. First argument is this, remaining arguments are passed as an array.
greet.apply(user, ['Hi', '?']); // 'Hi, Alice?'
// Useful trick: spread an array
const nums = [3, 1, 4, 1, 5, 9];
Math.max.apply(null, nums); // 9 (same as Math.max(...nums))
bind
Does not invoke immediately. Returns a new function with this permanently bound to the specified object.
const greetAlice = greet.bind(user, 'Hey');
greetAlice('!'); // 'Hey, Alice!'
greetAlice('.'); // 'Hey, Alice.'
// Common use: event handlers in React class components
class Button extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick() { /* this correctly points to the component */ }
}
Comparison
| Method | Invocation | Arguments | Return value |
|---|---|---|---|
call |
Immediate | Individual | Function result |
apply |
Immediate | Array | Function result |
bind |
Deferred | Individual (partial) | New function |
Memory Trick
call→ Comma-separated argumentsapply→ Array of argumentsbind→ Bindsthis(does not execute immediately)
✦ AI Mock Interview
Type your answer and get instant AI feedback
Sign in to use AI scoring
