SoFunction
Updated on 2025-04-12

Summary of the use of .call in JavaScript

In JavaScript, .call() is a method that explicitly sets the context (this value) of the function when it is executed and calls the function immediately. It is one of the built-in methods of function objects, similar to .apply() and .bind() .

Basic syntax of .call()

(thisArg, arg1, arg2, ...);
  • functionName: The function that calls .call().
  • thisArg: This value specified when functionName is called. If null or undefined, this will point to the global object (window in browser and undefined in strict mode).
  • arg1, arg2, …: Parameters passed when calling functionName

The basic functions of .call()

  • The .call() method will execute the function immediately
  • ThisArg will be assigned as this function execution
  • The subsequent parameters will be passed to the function in turn

The role of .call()

1. Explicit binding this

.call() can explicitly specify this pointer when a function is called

function greet(greeting) {
    (`${greeting}, my name is ${}`);
}
const person = { name: 'Alice' };
(person, 'Hello'); // Output: Hello, my name is Alice

Here the greet function this is set to person, so it can be accessed.

2. Inheritance and reuse methods

You can use .call() to borrow the method of one object to another.

const obj1 = {
    name: 'Object1',
    sayName() {
        ();
    }
};
const obj2 = { name: 'Object2' };
(obj2); // Output: Object2

3. Call the constructor or parent class method

In object-oriented programming, use .call() to call the constructor or method of the parent class.

function Animal(name) {
     = name;
}
function Dog(name, breed) {
    (this, name); // Call the parent class constructor     = breed;
}
const myDog = new Dog('Rex', 'Golden Retriever');
(); // Output: Rex

4. Functional programming and parameter expansion

.call() can be used to pass parameters in an explicit way without creating new arrays.

function sum(a, b, c) {
    return a + b + c;
}
((null, 1, 2, 3)); // Output: 6

Summarize

The key point of .call() is to explicitly set this value of the function and execute it immediately, which is suitable for the following scenarios:

  • Dynamically bind this context.
  • Multiplexing methods or functions.
  • Call the parent class method in an inheritance or combination scenario.
  • Pass parameters explicitly, rather than array form (difference from .apply())

This is the end of this article about the use of .call() in JavaScript. For more related JavaScript .call() content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!