What is call() method in JavaScript

Recently I wrote post on What is Bind method in JavaScript . In this post we will take a look on call method in JavaScript.

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


function GreetingMessage() {

alert("Hello Geek !");
 };

And you have an object Student as following,


var Student = {};

You can call function GreetingMessage on object Student as following,


GreetingMessage.call(Student);

As output you should get following output,

clip_image001

First argument of call() method is object. After second argument onwards are values to the functions being invoked. So if you have a function as following with parameter.


function GreetingMessage(name) {

alert("Hello "+ name);
 };

var Student = {};

GreetingMessage.call(Student,"dj");

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

image

First argument you pass in call() method can be referred with this operator in function. Consider below example, in this we are accessing property of object with this in function.

 function GreetingMessage() {

alert("Hello "+ this.name);
 };

var Student = {

name :"dj"

};

GreetingMessage.call(Student);

To summarize,

  • Call() method takes at least one parameter.
  • First parameter is object on which function to be invoked
  • Second parameter onwards get passed to the function to be invoked.

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

Published by

Dhananjay Kumar

Dhananjay Kumar is Developer Evangelist for Infragistics. He is a 8 times Microsoft MVP and well respected Developer Advocate in India.He is the author of 900+ Blog Posts, and can often be found speaking around India at conferences and hosting free workshops for programmers across the country. So far, he has hosted 60 free workshops on various topics like JavaScript, Angular, WCF, ASP.NET MVC, C#, Azure etc. Follow him on twitter @debug_mode for all the updates about his blog posts and workshops. You can send him email at debugmode [at] outlook [dot] com

3 thoughts on “What is call() method in JavaScript”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s