bugl
bugl
HomeLearnPatternsSearch
HomeLearnPatternsSearch

Loading lesson path

Learn/JavaScript/Objects, Classes, and Advanced Patterns
JavaScript•Objects, Classes, and Advanced Patterns

JavaScript Function apply()

Method Reuse

The apply()

method lets you write a method that can be used on different objects.

The apply()

method is used to call a function with a specific this.

The apply()

method is similar to call(), but it passes arguments in an array. apply() is an advanced topic.

Make sure you understand this and call()

before continuing.

The this

Keyword

The call()

Method

Basic apply() Syntax

The apply()

method is used to call a function with an object as an argument.

The apply()

method takes this as the first argument. The second argument is an array of values passed to the function.

The apply()

method is similar to the call() method (previous chapter). Syntax functionName.apply(

this, [arg1, arg2, ...]);

Using apply() to Set this

' When you use apply(), you can decide what this should refer to. In the example below, the greet function returns a greeting + this.name. When you use apply(), you decide that this should be the person3 object.

Example

const person1 = { name: "John" };
const person2 = { name: "Paul" };
const person3 = { name: "Ringo" };
function greet(greeting) {
return greeting + " " + this.name;
}
greet.apply(person3, ["Hello"]);

The Difference Between call() and apply()

The only difference between apply()

and call() is how arguments are passed.

The call()

method takes arguments separately.

The apply()

method takes arguments as an array.

Use apply()

when your arguments are already stored in an array.

Example greet.call(person, "Hello");
greet.apply(person, ["Hello"]);

Borrowing a Method from Another Object

You can use apply()

to borrow a method from another object:

Example 1

Apply the fullName method of person on person1

// Create a person Object const person = {

fullName

: function() {
return this.firstName + " " + this.lastName;
}
}
// Create a person1 Object const person1 = {
firstName:"John", lastName: "Doe"
}
// Create a person2 Object const person2 = {
firstName:"Mary", lastName: "Doe"
}
// This will return "John Doe":
person.fullName.apply(

person1

);
In these 2 examples, the apply() method behaves exactly the same as the call() method.

Example 2

Apply the fullName method of person on person2

// Create a person Object const person = {

fullName

: function() {
return this.firstName + " " + this.lastName;
}
}
// Create a person1 Object const person1 = {
firstName:"John", lastName: "Doe"
}
// Create a person2 Object const person2 = {
firstName:"Mary", lastName: "Doe"
}
// This will return "Mary Doe"
person.fullName.call(

person2

);

Previous

JavaScript PlainDateTime

Next

JavaScript Object Constructors