What is method borrowing, and how do call and apply let you do it?
Method borrowing means using a method from one object on another by passing the other as this with call or apply. A classic case is Array.prototype.slice.call(arguments) on an array-like object.
Explain it simply
You borrow a neighbour's pressure cooker without owning one. A method does not belong to its object permanently; it only needs a this that has the right shape. If you give an array method an array-like object (one with indexed items and a length), it works fine.
Two classic uses: turning arguments or a NodeList into a real array, and Math.max.apply(null, array) from the days before spread syntax. null is passed as this because Math.max does not use it.
Today, Array.from(arrayLike) and Math.max(...arr) are cleaner, but the idea of borrowing still appears in interviews.
Example
function tail() {
return Array.prototype.slice.call(arguments, 1);
}
console.log(tail(1, 2, 3)); // Output: [2,3]
const arrayLike = { 0: "a", 1: "b", length: 2 };
const upper = Array.prototype.map.call(arrayLike, (x) => x.toUpperCase());
console.log(upper); // Output: ["A","B"]
console.log(Math.max.apply(null, [3, 9, 4])); // Output: 9
console.log(Math.max(...[3, 9, 4])); // Output: 9What to say in the interview
"Borrowing means calling a method of one object with another object as this, using call or apply, so Array.prototype.slice.call(arguments) works on array-likes. The method only needs this to be indexed with a length. In modern code I'd use Array.from or spread instead."
Common mistakes
- Trying arr.map directly on a NodeList or arguments object. They are not arrays, so the method does not exist on them.