Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

Function apply

Method Reuse

Using the apply() method, you can write a function that can be applied to different objects by passing different this values.

The JavaScript apply() Method

The apply() method is similar to the call() method (as discussed in the previous chapter).

In this example, the fullName method of person is applied to person1.

Example

const person = {
  fullName: function() {
    return this.firstName + ” “ + this.lastName;
  }
}

const person1 = {
  firstName: “Mary”,
  lastName: “Doe”
}

// This will return “Mary Doe”:
person.fullName.apply(person1);

The Difference Between call() and apply()

The difference is:

The call() method accepts arguments individually.

The apply() method accepts arguments as an array.

The apply() method is useful when you want to pass an array as arguments instead of a separate list of arguments.

The apply() Method with Arguments

The apply() method accepts arguments as an array.

Example

const person = {
  fullName: function(city, country) {
    return this.firstName + ” “ + this.lastName “,” + city + “,” + country;
  }
}

const person1 = {
  firstName:“John”,
  lastName: “Doe”
}

person.fullName.apply(person1, [“Oslo”“Norway”]);

In comparison to the call() method:

Example

const person = {
  fullName: function(city, country) {
    return this.firstName + ” “ + this.lastName “,” + city + “,” + country;
  }
}

const person1 = {
  firstName:“John”,
  lastName: “Doe”
}

person.fullName.call(person1, “Oslo”“Norway”);

Simulate a Max Method on Arrays

You can find the largest number in a list of numbers using the Math.max() method.

Example

Math.max(1,2,3);  // Will return 3

Since JavaScript arrays do not have a max() method, you can use the Math.max() method with the array elements.

Example

Math.max.apply(null, [1,2,3]); // Will also return 3

The first argument (null) is irrelevant in this example, as it is not used.

These examples will produce the same result:

Example

Math.max.apply(Math, [1,2,3]); // Will also return 3

Example

Math.max.apply(” “, [1,2,3]); // Will also return 3

Example

Math.max.apply(0, [1,2,3]); // Will also return 3

JavaScript Strict Mode

In JavaScript strict mode, if the first argument of the apply() method is not an object, it is treated as undefined and does not become the owner of the invoked function. In non-strict mode, it becomes the global object.