call, apply, bind
All three control what this refers to when calling a function.
call - invoke immediately with args spread
js
function greet(greeting, punctuation) {
return `${greeting}, ${this.name}${punctuation}`;
}
const user = { name: 'Alice' };
greet.call(user, 'Hello', '!'); // 'Hello, Alice!'apply - invoke immediately with args as array
js
greet.apply(user, ['Hello', '!']); // 'Hello, Alice!'
// useful for spreading arrays into functions
const nums = [3, 1, 4, 1, 5];
Math.max.apply(null, nums); // 5
// modern equivalent: Math.max(...nums)bind - returns a new function with this locked
js
const greetAlice = greet.bind(user, 'Hello');
greetAlice('!'); // 'Hello, Alice!'
greetAlice('?'); // 'Hello, Alice?'
// common use case - preserving this in callbacks
class Timer {
constructor() { this.count = 0; }
start() {
setInterval(this.tick.bind(this), 1000);
}
tick() { this.count++; }
}Comparison
| Invokes immediately | Args format | Returns | |
|---|---|---|---|
call | Yes | Spread | Result |
apply | Yes | Array | Result |
bind | No | Spread | New function |
In modern code
bindis often replaced by arrow functions (() => this.tick()), andapplyis replaced by the spread operator. But understanding all three is essential for interviews.
updated
did you know it?