JavaScript Function call()
14 April 2025 | Category: JavaScript
In JavaScript, the call()
method is a built-in function method that allows you to call a function with a specific this
value and pass arguments one by one.
It’s useful when you want to borrow a function from one object and use it in the context of another object.
đ§ Syntax
functionName.call(thisArg, arg1, arg2, ...);
Parameters:
thisArg
: The value to use asthis
when the function is called.arg1, arg2, ...
: Arguments passed to the function.
â Basic Example
function greet(city) {
console.log(`Hi, I'm ${this.name} from ${city}`);
}
const person = { name: "Alice" };
greet.call(person, "New York"); // Hi, I'm Alice from New York
đ§Š greet
isn’t a method of person
, but using call()
sets this
to person
.
𧲠Why Use call()
?
- Function borrowing
- Controlling the context (
this
) - Reusability across multiple objects
đ call()
vs apply()
Feature | call() | apply() |
---|---|---|
Arguments | Passed individually | Passed as an array |
Example | func.call(obj, a, b) | func.apply(obj, [a, b]) |
greet.call(person, "Delhi");
greet.apply(person, ["Delhi"]);
đ§Ź Function Borrowing Example
const user1 = {
name: "John",
greet: function () {
console.log(`Hello, I'm ${this.name}`);
}
};
const user2 = { name: "Emma" };
user1.greet.call(user2); // Hello, I'm Emma
đŚ Using call()
with Built-in Methods
const numbers = [5, 2, 8, 1];
const max = Math.max.call(null, ...numbers);
console.log(max); // 8
đ Real-world Use Case: Inheritance
function Animal(name) {
this.name = name;
}
function Dog(name, breed) {
Animal.call(this, name); // Call Animal with Dog's this
this.breed = breed;
}
const myDog = new Dog("Buddy", "Labrador");
console.log(myDog); // { name: "Buddy", breed: "Labrador" }
â ď¸ Notes
call()
does not create a new function, it simply executes the existing function with a new context.- If
null
orundefined
is passed as thethisArg
, it defaults to the global object in non-strict mode or remainsundefined
in strict mode.
đ§ž Summary
- The
call()
method lets you invoke functions while explicitly setting thethis
context. - It’s extremely useful for function reuse, inheritance, and dynamic method calls.