Introduction
JavaScript call() method is used to invoke a function while explicitly specifying the value of this inside that function. It allows a function to use properties and methods from a chosen object without permanently attaching the function to that object. The method is especially useful when sharing behavior between objects, borrowing built-in methods, and controlling the execution context of regular functions. The call() method is available on functions through Function.prototype and accepts the target this value followed by the function’s arguments individually.
JavaScript call() Method Syntax
The syntax of the call() method is:
functionName.call(thisArg, arg1, arg2, ...);
thisArg: The value to use asthiswhen the function executes.arg1, arg2, ...: Optional arguments passed to the function individually, in the order expected by its parameters.
The function is executed immediately, and call() returns the value returned by that function. If the function does not explicitly return a value, the result is undefined.
Basic Example of JavaScript call()
Consider a function that reads a name property from this. Calling the function normally makes its this value depend on how it is invoked. With call(), you can provide an object explicitly.
function introduce() {
console.log(`My name is ${this.name}`);
}
const user = {
name: "Alex"
};
introduce.call(user); // My name is Alex
In this example, user becomes the this value while introduce() runs. The function itself is not added to the user object; it is simply invoked with that object as its execution context.
Passing Arguments with call()
The call() method can pass arguments after the first parameter. Each argument is supplied separately rather than as an array.
function calculateTotal(price, quantity) {
return this.currency + (price * quantity);
}
const product = {
currency: "$"
};
const total = calculateTotal.call(product, 25, 3);
console.log(total); // $75
Here, product is used as this, while 25 and 3 are passed to the function’s price and quantity parameters. This makes it possible to reuse one function with different objects and input values.
Using call() to Borrow a Method
Method borrowing means using a method that belongs to one object with another object. The call() method makes this possible without copying the method or changing either object.
const personOne = {
firstName: "John",
lastName: "Smith",
fullName: function () {
return this.firstName + " " + this.lastName;
}
};
const personTwo = {
firstName: "Emma",
lastName: "Brown"
};
console.log(personOne.fullName()); // John Smith
console.log(personOne.fullName.call(personTwo)); // Emma Brown
The fullName() method is defined only on personOne, but it can read the properties of personTwo when invoked with call(). This pattern is useful when multiple objects share the same data structure or behavior.
Sharing Functions Between Multiple Objects
You can define a standalone function and reuse it with several objects. This avoids repeating the same method implementation.
function showDetails() {
return `${this.name} works as a ${this.role}.`;
}
const employee = {
name: "Sara",
role: "Developer"
};
const manager = {
name: "David",
role: "Project Manager"
};
console.log(showDetails.call(employee));
console.log(showDetails.call(manager));
The same function produces different results because the this value changes for each call. This is one of the main reasons developers use call().
Using call() with Built-in Methods
JavaScript’s built-in methods can sometimes be borrowed to work with values that do not have the method directly available. For example, Array.prototype.slice() can create an array from an array-like object.
function listArguments() {
const args = Array.prototype.slice.call(arguments);
console.log(args);
}
listArguments("HTML", "CSS", "JavaScript");
// ["HTML", "CSS", "JavaScript"]
The arguments object is array-like: it has indexed values and a length property, but it is not a real array and does not provide every array method. Borrowing slice() converts its values into a new array. In modern code, rest parameters are usually a clearer alternative:
function listItems(...items) {
console.log(items);
}
listItems("HTML", "CSS", "JavaScript");
Using call() with JavaScript Inheritance Patterns
Before ES6 classes became common, constructor functions often used call() to invoke another constructor and initialize properties on the new object.
function Person(name) {
this.name = name;
}
function Employee(name, jobTitle) {
Person.call(this, name);
this.jobTitle = jobTitle;
}
const employee = new Employee("Mia", "Developer");
console.log(employee.name); // Mia
console.log(employee.jobTitle); // Developer
When Employee is called with new, its this value refers to the newly created employee object. Calling Person with that same value initializes the inherited name property. This pattern shares constructor initialization, but it does not by itself establish prototype inheritance. Modern JavaScript generally uses class and extends for this purpose.
What Happens When thisArg Is null or undefined?
If null or undefined is passed as the first argument to call(), the result depends on whether the function runs in strict mode.
function showThis() {
console.log(this);
}
showThis.call(null);
showThis.call(undefined);
In non-strict mode, a nullish thisArg is substituted with the global object. In strict mode, the supplied value is preserved, so this remains null or undefined.
"use strict";
function showStrictThis() {
console.log(this);
}
showStrictThis.call(null); // null
showStrictThis.call(undefined); // undefined
Strict mode also prevents primitive thisArg values from being automatically converted to wrapper objects.
Using Primitive Values as thisArg
When a primitive value such as a string or number is passed to a regular function through call(), non-strict and strict functions handle it differently.
function showValue() {
console.log(this);
}
showValue.call("JavaScript");
In non-strict mode, JavaScript converts primitive values to their corresponding wrapper objects when setting this. In strict mode, the primitive value is used as supplied.
"use strict";
function showPrimitive() {
console.log(typeof this);
}
showPrimitive.call("JavaScript"); // string
This distinction matters when a function depends on the exact type of its this value.
call() Does Not Change an Arrow Function’s this
Arrow functions do not create their own this binding. Instead, they capture this from the surrounding lexical scope. As a result, using call() cannot replace the this value of an arrow function.
const user = {
name: "Olivia"
};
const arrowFunction = () => {
console.log(this);
};
arrowFunction.call(user);
The arrow function does not use user as its this value. If you need to explicitly choose a function’s this, use a regular function rather than an arrow function.
Difference Between call(), apply(), and bind()
The call(), apply(), and bind() methods are related because they control the this value of regular functions. Their main difference is how and when the function is executed and how arguments are supplied.
| Method | Execution | Arguments | Return value |
|---|---|---|---|
call() |
Executes immediately | Passed individually | Function’s result |
apply() |
Executes immediately | Passed as an array or array-like value | Function’s result |
bind() |
Does not execute immediately | Can be supplied now or later | A new bound function |
Example of call():
function greet(city, country) {
return `${this.name} lives in ${city}, ${country}.`;
}
const user = { name: "Noah" };
console.log(greet.call(user, "Dhaka", "Bangladesh"));
Example of apply():
console.log(greet.apply(user, ["Dhaka", "Bangladesh"]));
Example of bind():
const greetUser = greet.bind(user, "Dhaka");
console.log(greetUser("Bangladesh"));
Choose call() when you want immediate execution and individual arguments, apply() when arguments are already grouped in an array-like value, and bind() when you need a reusable function with a fixed this value.
Important Behavior of call() with Bound Functions
If a function has already been created with bind(), its bound this value cannot normally be replaced by calling it with another thisArg.
function showName() {
console.log(this.name);
}
const firstUser = { name: "Ava" };
const secondUser = { name: "Liam" };
const boundFunction = showName.bind(firstUser);
boundFunction.call(secondUser); // Ava
The function continues to use firstUser because bind() created a function with a fixed this binding. The extra thisArg supplied to call() is ignored for that binding.
Using call() with Function Return Values
The call() method returns whatever the invoked function returns. You can store that result in a variable, pass it to another function, or use it in an expression.
function getArea(width, height) {
return this.unit + (width * height);
}
const measurement = { unit: " square units: " };
const area = getArea.call(measurement, 8, 5);
console.log(area); // square units: 40
If the called function throws an error, the error propagates from the call() expression just as it would from a normal function invocation.
When call() Cannot Be Used to Invoke a Function
The call() method invokes callable functions. It cannot turn a non-callable value into a function. For example, attempting to access and invoke call() on a number or a plain object will result in a TypeError.
const value = 10;
// value.call(null); // TypeError: value.call is not a function
Also, class constructors cannot be invoked as ordinary functions. Calling a class constructor with call() throws a TypeError; class constructors must be invoked with new.
class Product {
constructor(name) {
this.name = name;
}
}
const item = new Product("Laptop");
// Product.call({}, "Phone"); // TypeError
Use new to create class instances and use call() for ordinary callable functions that need an explicitly supplied this value.
JavaScript call() Method: Practical Example
The following example demonstrates how one reusable function can calculate the discounted price for different product objects.
function getDiscountedPrice(discount) {
const discountAmount = this.price * discount / 100;
return this.price - discountAmount;
}
const laptop = {
name: "Laptop",
price: 800
};
const phone = {
name: "Phone",
price: 500
};
console.log(getDiscountedPrice.call(laptop, 10)); // 720
console.log(getDiscountedPrice.call(phone, 20)); // 400
The function does not need to know which product it is processing. The object passed to call() supplies the price through this, and the discount percentage is passed as a regular argument. This keeps the calculation reusable for different product objects.