JavaScript Function Apply

Course recommendation:

method reuse apply() By

Methods, you can write methods for different objects.

apply() JavaScript apply() method call() Methods similar to

The methods are very similar:In this example, person of The method isapplicationto person1:

Example

var person = {
    fullName: function() {
        return this.firstName + \" \" + this.lastName;
    }
}
var person1 = {
    firstName: "Bill",
    lastName: "Gates",
}
person.fullName.apply(person1);  // It will return "Bill Gates"

Try It Yourself

The difference between call() and apply()

The difference is:

call() Method accepts parameters separately.

apply() Method accepts parameters in array form.

If you want to use an array instead of a parameter list, then apply() The method is very convenient.

Parameterized apply() method

apply() Method accepts parameters in an array form:

Example

var person = {
  fullName: function(city, country) {
    return this.firstName + \" \" + this.lastName + "," + city + "," + country;
  }
}
var person1 = {
  firstName:\"Bill\",
  lastName: "Gates"
}
person.fullName.apply(person1, ["Oslo", "Norway"]);

Try It Yourself

with call() Method Comparison:

Example

var person = {
  fullName: function(city, country) {
    return this.firstName + \" \" + this.lastName + "," + city + "," + country;
  }
}
var person1 = {
  firstName:\"Bill\",
  lastName: "Gates"
}
person.fullName.call(person1, "Oslo", "Norway");

Try It Yourself

to simulate the max method on an array

You can use Math.max() Method finds the largest number in the (number list):

Example

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

Try It Yourself

Since JavaScript arrays do not have a max() method, you can apply Math.max() Method.

Example

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

Try It Yourself

The first parameter (null) is irrelevant. It is not used in this example.

These examples will give the same result:

Example

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

Try It Yourself

Example

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

Try It Yourself

Example

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

Try It Yourself

JavaScript Strict Mode

In JavaScript strict mode, if apply() If the first parameter is not an object, it will become the owner (object) of the function to be called. In 'non-strict' mode, it becomes the global object.