JavaScript Function call() Method

The `call()` method in JavaScript is used to invoke a function with a specified `this` value and arguments provided individually (not as an array). This allows you to call a function with a particular context, ensuring that `this` refers to the object you want it to.

Key Features of call():

Example of call() Method:

This example demonstrates how to use the `call()` method to call a function with a specified `this` value:

Example


function greet() {
    console.log("Hello, " + this.name);
}

const person = { name: "John" };

greet.call(person);  // Hello, John
                                                

Output

Hello, John

Passing Arguments with call():

You can pass arguments to the function using the `call()` method. Here’s an example:

Example


function multiply(a, b) {
    return a * b;
}

console.log(multiply.call(null, 2, 3));  // 6          
                        

Output

6

When to Use call():

The `call()` method is useful when you want to invoke a function with a specific context (i.e., `this`) and pass arguments individually. It's commonly used when you want to borrow methods from other objects or in situations like event handling where `this` needs to refer to a specific object.

Resources to Learn More About call():