apply()
方法使用在数组形式提供的 this
关键字值和参数来调用一个函数。
示例
// object definition
const personName = {
firstName: "Taylor",
lastName: "Jackson",
};
// function definition
function greet(wish, message) {
return `${this.firstName}, ${wish}. ${message}`;
}
// calling greet() function by passing two arguments
let result = greet.apply(personName, ["Good morning", "How are you?"]);
console.log(result);
// Output:
// Taylor, Good morning. How are you?
apply() 语法
apply()
方法的语法是
func.apply(thisArg, argsArray)
其中,func
是一个函数。
apply() 参数
apply()
方法可以接受两个参数
thisArg
- 在调用func
时提供的this
值。argsArray
(可选) - 一个包含函数参数的数组。
apply() 返回值
- 返回使用指定的
this
值和参数调用的函数的结果。
示例 1:使用 apply() 方法调用函数
// object definition
const personName = {
firstName: "Taylor",
lastName: "Jackson",
};
// function definition
function greet(wish, message) {
return `${this.firstName}, ${wish}. ${message}`;
}
// calling greet() function by passing two arguments
let result = greet.apply(personName, ["Good morning", "How are you?"]);
console.log(result);
输出
Taylor, Good morning. How are you?
在上面的程序中,我们使用 apply()
方法调用了 greet()
函数。
在 apply()
方法内部,参数
- personName - 是
this
值 ["Good morning", "How are you?"]
- 是greet()
函数的"wish"
和"message"
参数的值
该方法调用 greet()
函数,因此 result 变量保存了 greet()
的返回值。
除了调用函数,我们还可以使用 apply()
方法来
- 函数借用
- 追加数组
示例 2:使用 apply() 进行函数借用
// object definition
const car = {
name: "BMW",
description() {
return `The ${this.name} is of ${this.color} color.`;
},
};
// object definition
const bike = {
name: "Duke",
color: "black",
};
// bike is borrowing description() method from car using apply()
let result = car.description.apply(bike);
console.log(result);
输出
The Duke is of black color.
在上面的程序中,我们借助 apply()
方法将 car
对象的函数借用到 bike
对象中。
示例 3:使用 apply() 追加两个数组
let color1 = ["Red", "Green", "Blue"];
let color2 = ["Yellow", "Black"];
// appending two arrays color1 and color2
color1.push.apply(color1, color2);
console.log(color1);
输出
[ 'Red', 'Green', 'Blue', 'Yellow', 'Black' ]
示例 4:在内置函数中使用 apply()
const numbers = [5, 1, 4, 3, 4, 6, 8];
// using apply() with Math object
let max = Math.max.apply(null, numbers);
console.log(max);
// without using apply() with Math object
let max1 = Math.max(5, 1, 4, 3, 4, 6, 8);
console.log(max1);
输出
8 8