What are the Call and Apply Methods in JavaScript

Read full article on the Infragistics blog

In JavaScript, the apply() and call() methods execute a function in the context (scope) of the first argument you pass to them. Let’s take a look at them in action to learn more. Say that you have an object person as shown below:

And in addition, you have a function message as shown below:

Now, you have a requirement to pass the person object as the value of this in the function. In addition to explicitly passing the value of this, you also need to pass the value for the age parameter.

You can pass the context (the value of this) explicitly using by either the call() or apply() methods. Consider the following code:

Using the call method, we are passing the object person as the value of this inside message function.  You can achieve the same using the apply() method as shown in the listing below:

In JavaScript, the call() and apply() methods work in almost exactly the same way, but with a few key differences:

  1. The first parameter of both call() and apply() is the value of this object.
  2. In the call() method, the other arguments to function will be passed as separate comma separated values.
  3. The call() method takes zero or more individual parameters.
  4. In the apply() method, the second parameter is an array.
  5. The apply() method takes an array of parameter.
  6. You should use the call() method when the number of function parameters is fixed.
  7. You should use the apply() method, when the number of function parameters is not fixed.

 

Read full article on the Infragistics blog

One thought on “What are the Call and Apply Methods 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 )

Connecting to %s