JavaScript call() Function Tutorial

In this section, we will learn what the call() function is and how to use it in JavaScript.

What is JavaScript call() Function?

As mentioned before, functions in JavaScript are object.

There are a couple of useful methods, and properties already built for functions.

One of them is the `call` method.

When there’s a function that used the `this` keyword in its body, we can use the `call` method to explicitly define what object the `this` keyword should bind to.

JavaScript call() Function Syntax:

function.call(object, args...)

call() Function Parameters:

The `call` method takes multiple arguments. But the first argument should be the name of the object in which we want to bind the `this` keyword of the target function to that object.

Also, the rest of arguments that we set for this method are actually the arguments we want to set for the target function.

call() Function Return Value:

The return value of the call() function is the same as the function that invoked the call().

Example: using call() function in JavaScript

const obj = {
  firstName: "John"
}
function changeName(name){
  this.firstName = name;
}
changeName.call(obj, "Omid");
console.log(obj.firstName);

Output:

Omid

Here there’s an object named `obj` that has one property named `firstName`. The value of this property is `John`. So if we call the `console.log()` and put this property as its argument, we will get the value `John` on the console.

But before doing so, we called the `call` method first:

changeName.call(obj, "Omid");

As mentioned before, the `call()` method is a method of functions and so we can call them via the name of that function.

Also, as you can see, for the first argument, we set the object `obj`. This means we want for this particular call to bind the `this` keyword to the `obj`.

After that, we set another argument and this is because the `changeName` function has one parameter and so our second argument in the `call` method will be assigned to the `name` parameter of the `changeName` function.

At the end when we called the `console.log(obj.firstName);` we can see that the value of the `firstName` changed to `Omid`.

Note: check the `this` keyword section if you’re not familiar with how this keyword binds with objects.

More to Read: 

JavaScript apply() function tutorial 

JavaScript bind() function tutorial 

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies