The call() Method in JavaScript
🔍 What is call()?
The call() method is a built-in function available on all JavaScript functions. It allows you to invoke a function and explicitly set its this value, followed by any arguments the function requires.
Note
💡 Think of call() as a way to temporarily "borrow" a function and run it in the context of a different object.
📌 Syntax
call() Syntax
functionName.call(thisArg, arg1, arg2, ...);- thisArg: The object to use as this when the function is called. - arg1, arg2, ...: Optional arguments passed to the function.
📦 Basic Example
Using call()
function greet(greeting) {
console.log(greeting + ", " + this.name);
}
const person = { name: "Alice" };
greet.call(person, "Hello"); // Hello, Alice🧬 Why Use call()?
- ⚙️ To control the value of this inside a function
- 🔄 To reuse methods across different objects
- 🔧 For dynamic method invocation
🎯 call() vs direct invocation
Comparison
function sayHi() {
console.log("Hi, " + this.name);
}
const user = { name: "Bob" };
sayHi(); // Hi, undefined (this is window/global)
sayHi.call(user); // Hi, BobNote
⚠️ Without call(), this may not point to the intended object in strict or global mode.
🔁 Borrowing Methods
Method Borrowing with call()
const person1 = {
fullName: function() {
return this.first + " " + this.last;
}
};
const person2 = {
first: "Charlie",
last: "Brown"
};
console.log(person1.fullName.call(person2)); // Charlie Brown🧪 call() with Multiple Arguments
call() with multiple arguments
function showDetails(age, country) {
console.log(this.name + " is " + age + " years old from " + country);
}
const user = { name: "Dora" };
showDetails.call(user, 25, "India");
// Dora is 25 years old from India📚 Summary Table
| Use Case | Description |
|---|---|
| Function Reuse | Reuse function logic with a different object |
| Set this | Define what this should refer to |
| Pass Arguments | Send arguments individually after thisArg |
🔗 Related Methods
>>“JavaScript’s power lies in flexibility — and call() is one of its sharpest tools.” 🛠️