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:


var person = {
name: 'dj'
};

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


function message(age) {
return `Hi ${this.name}, you are ${age} years old !`;
}

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:


function message(age) {
return `Hi ${this.name}, you are ${age} years old !`;
}
var person = {
name: 'dj'
};
var mes = message.call(person, 30);
console.log(mes); // Hi dj, you are 30 years old !

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:


function message(age) {
return `Hi ${this.name}, you are ${age} years old !`;
}
var person = {
name: 'dj'
};
var mes = message.apply(person, [30, 67]);
console.log(mes); // Hi dj, you are 30 years old !

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 response to “What are the Call and Apply Methods in JavaScript”

  1. […] Que sont les méthodes Call et Apply en JavaScript? […]

Leave a comment

Create a website or blog at WordPress.com