Borrowing Methods with call() and apply()
What You'll Learn
You'll discover how to use call() and apply() to borrow methods from one object and run them on a completely different object.
The Core Idea
Sometimes you have an object with a useful method, but you want to use that method on a different object that doesn't have it. Instead of duplicating the method code, you can "borrow" it using call() or apply().
Think of it like borrowing a neighbor's lawnmower. You don't own one, but you can still mow your lawn by borrowing theirs and using it on your property.
How It Works
When you call a method with call() or apply(), you explicitly set what this refers to inside that method:
const person = {
name: 'Alice',
greet: function() {
return `Hello, I'm ${this.name}`;
}
};
const anotherPerson = {
name: 'Bob'
// No greet method!
};
// Borrow the greet method
const greeting = person.greet.call(anotherPerson);
console.log(greeting); // "Hello, I'm Bob"
Here, anotherPerson doesn't have a greet method, but we borrowed it from person and made this point to anotherPerson.
Real-World Use
Borrowing is especially useful with built-in methods. For example, array methods can work on array-like objects:
function showArgs() {
// 'arguments' isn't a real array, but we can borrow slice
const argsArray = Array.prototype.slice.call(arguments);
console.log(argsArray);
}
showArgs(1, 2, 3); // [1, 2, 3]
Key Takeaway: call() and apply() let you borrow methods from one object and execute them on another by explicitly controlling this, avoiding code duplication.