Home  >  Article  >  Web Front-end  >  What is the usage of javascript apply

What is the usage of javascript apply

藏色散人
藏色散人Original
2021-10-29 14:06:551930browse

The function of javascript apply is to write methods for different objects; the apply() method accepts parameters in the form of an array, and its usage syntax is such as "person.fullName.apply(person1);".

What is the usage of javascript apply

The operating environment of this article: Windows 7 system, javascript version 1.8.5, DELL G3 computer

What is the usage of javascript apply?

JavaScript FunctionApply

Method Reuse

With the apply() method, you can write functions for different Object methods.

JavaScript apply() method

apply() method is very similar to call() method:

(Same function: both are to change something Exists in the context of a function running, in order to change the pointer of this inside the function body)

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

Instance

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

Note:

The difference between call() and apply()

The difference is:

## The #call() method accepts parameters respectively.

The apply() method accepts parameters in the form of an array.

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

Recommended study: "

javascript basic tutorial"

The above is the detailed content of What is the usage of javascript apply. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn