Topic 36 of 37
call, apply, bind
Overview
These three methods exist on the Function prototype. They allow you to manually set the 'this' context of a function. 'call' takes comma-separated arguments. 'apply' takes an array of arguments. 'bind' doesn't execute the function immediately; it returns a new function with the context locked in.
Syntax
A handy mnemonic: Call takes Commas, Apply takes Arrays.
Call vs apply vs bind
javascript
const person1 = { name: "Alice" };
const person2 = { name: "Bob" };
function introduce(greeting, punctuation) {
console.log(`${greeting}, ${this.name}${punctuation}`);
}
// .call(): pass args individually
introduce.call(person1, "Hello", "!"); // "Hello, Alice!"
// .apply(): pass args as an array
introduce.apply(person2, ["Hi", "."]); // "Hi, Bob."
// .bind(): returns a new function to call later
const introduceBob = introduce.bind(person2, "Welcome");
introduceBob("!!!"); // "Welcome, Bob!!!"Common Pitfalls
- You cannot re-bind an arrow function. `arrowFn.call(obj)` does absolutely nothing to its 'this' context.
Interview Tips
- Interviewers love asking how to find the max number in an array using Math.max. Answer: `Math.max.apply(null, [1, 2, 3])` (or modern ES6: `Math.max(...[1, 2, 3])`).
Real-World Example
Borrowing Array methods for Array-like objects (like arguments or NodeLists).
example
javascript
function sumArgs() {
// 'arguments' is not an array, it has no .reduce method
// So we borrow it from Array.prototype!
return Array.prototype.reduce.call(arguments, (acc, val) => acc + val, 0);
}