What is Call() Method in JavaScript

Recently I wrote the article What is Bind method in JavaScript. In this article we will have a look at the call method in JavaScript. 

Before reading this article, you may want to go through the following articles:

Using the call() method you can invoke a function on a given object. Let us understand with some examples. Consider that you have a function GreetingMessage() as in the following:

function GreetingMessage() {
    alert("Hello Geek !");
};

And you have an object Student as in the following:

var Student = {};

You can call the function GreetingMessage on the object Student as in the following:

GreetingMessage.call(Student);

As output you should get the following output:

image3.gif

The first argument of the call() method is an object. After the second argument onward are values to the functions being invoked. So you have a function as in the following with a parameter:

function GreetingMessage(name) {
    alert("Hello "+ name);
};
var Student = {};
GreetingMessage.call(Student,"dj"
);

We are passing dj as the second argument of the call method. So it becomes a parameter to the GreetingMessage() function. You will get output from the code snippet above as in the following

image4.gif
 
The first argument you pass in the call() method can be referred to with the "this" operator in the function. Consider the following example, in this we are accessing the property of the object with the this operator in the function.

function GreetingMessage() {
        alert("Hello "+ this.name);
     };
     var Student = {
     name :"dj"
};
GreetingMessage.call(Student
)

To summarize:

  1. The Call() method takes at least one parameter.
  2. The first parameter is an object on which the function is to be invoked.
  3. The second parameter onward is passed to the function to be invoked.

This was a brief introduction of the call() method in JavaScript. I hope you find this article useful. Thanks for reading.

Up Next
    Ebook Download
    View all
    Learn
    View all