4 min read
•Question 13 of 50mediumWhat are call(), apply(), and bind()?
Understanding explicit function binding.
What You'll Learn
- How call, apply, bind work
- Differences between them
- Use cases
Comparison
| Method | Execution | Arguments |
|---|---|---|
| call() | Immediate | Comma-separated |
| apply() | Immediate | Array |
| bind() | Returns new function | Comma-separated |
Examples
code.jsJavaScript
function greet(greeting, punctuation) {
console.log(greeting + ', ' + this.name + punctuation);
}
const person = { name: 'John' };
// call - immediate, individual args
greet.call(person, 'Hello', '!');
// 'Hello, John!'
// apply - immediate, array of args
greet.apply(person, ['Hi', '?']);
// 'Hi, John?'
// bind - returns new function
const greetJohn = greet.bind(person, 'Hey');
greetJohn('!'); // 'Hey, John!'Use Cases
code.jsJavaScript
// Borrowing methods
const arrayLike = { 0: 'a', 1: 'b', length: 2 };
const arr = Array.prototype.slice.call(arrayLike);
// ['a', 'b']
// Max of array
const nums = [1, 5, 3, 9, 2];
Math.max.apply(null, nums); // 9
// Event handlers (preserve this)
class Button {
constructor() {
this.clicked = false;
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.clicked = true;
}
}