How To Use JavaScript’s call(), apply(), & bind() Methods

JavaScript is a versatile and dynamic language that provides several mechanisms for manipulating function contexts and arguments. Among these mechanisms are three important methods: call, apply, and bind.

The .call(), .apply(), and .bind() methods allow developers to explicitly control the value of this within a function and provide a way to pass arguments in a flexible manner.

Before going further, you need to know what is “this” in JavaScript and how it works, then you can properly understand the work of these methods.

1. call() Method

The call method is used to invoke a function with a specific this value and individual arguments. Its syntax is as follows:

function.call(thisArg, arg1, arg2, ...)

Here, thisArg is the value that will be used as this when executing the function, and arg1, arg2, etc., are the arguments to be passed to the function.

Example of the call() Method:

function greet(name) {
    console.log(`Hello, ${name}! I am ${this.name}`);
}

const person = { name: 'John' };

greet.call(person, 'Alice'); // Outputs: Hello, Alice! I am John

In this example, the call method is used to invoke the greet function with person as the value of this, and 'Alice' as the argument.

2. apply() Method

The apply method is similar to call, but it takes an array-like object as the second parameter, where each element of the array is passed as an argument to the function. Its syntax is as follows:

function.apply(thisArg, [argsArray])

Here, thisArg is the value that will be used as this, and argsArray is an array-like object containing the arguments to be passed.

Example of the apply Method:

function greet(name) {
    console.log(`Hello, ${name}! I am ${this.name}`);
}

const person = { name: 'John' };

greet.apply(person, ['Alice']); // Outputs: Hello, Alice! I am John

In this example, the apply method is used similarly to call, but the arguments are passed in an array.

3. bind() Method

The bind method is used to create a new function that, when called, has its this keyword set to a specific value. It also allows pre-setting some or all of the function’s arguments. Its syntax is as follows:

function.bind(thisArg, arg1, arg2, ...)

Here, thisArg is the value that will be used as this when the new function is called, and arg1, arg2, etc., are optional arguments to be pre-set.

Example of the bind Method:

function greet(name) {
    console.log(`Hello, ${name}! I am ${this.name}`);
}

const person = { name: 'John' };

const greetPerson = greet.bind(person);
greetPerson('Alice'); // Outputs: Hello, Alice! I am John

In this example, the bind method is used to create a new function (greetPerson) with person as the value of this. When greetPerson is called, it automatically uses person as its context.