The call() Method
What you'll learn: How to use call() to invoke a function and explicitly tell it what this should be.
The Problem It Solves
You've seen how easily this gets lost when you pass methods around as callbacks or extract them from objects. The call() method lets you manually control what this points to when you invoke a function.
How call() Works
Every function in JavaScript has a built-in call() method. When you use it, you're saying: "Run this function, but use THIS specific value as this inside it."
Syntax:
functionName.call(thisArg, arg1, arg2, ...);
- First argument: What
thisshould be - Remaining arguments: Normal function arguments, passed individually
Example: Rescuing a Lost Context
const person = {
name: 'Alice',
greet: function(greeting) {
console.log(greeting + ', ' + this.name);
}
};
const greet = person.greet; // Method extracted, 'this' will be lost
greet('Hello'); // Error or "Hello, undefined"
greet.call(person, 'Hello'); // "Hello, Alice" ✓
By using call(person, 'Hello'), we explicitly set this to person inside the greet function.
Borrowing Methods
You can even use call() to "borrow" a method from one object and use it with another:
const dog = {
name: 'Buddy',
speak: function() {
console.log(this.name + ' barks');
}
};
const cat = { name: 'Whiskers' };
dog.speak.call(cat); // "Whiskers barks"
The speak method was defined on dog, but we ran it with cat as this.
Key Takeaway: call() lets you invoke any function with an explicit this value and individual arguments, giving you complete control over context binding.