JavaScript apply() 函数
JavaScript apply()
方法是 Function 对象的一个方法,通过 apply()
调用函数可以指定函数内部 this
的值,这让函数/方法能在更多的场景下正确执行。
apply()
与 call()
类似,支持参数传递的方式不同, apply()
接受的是包含多个参数的数组,而 call()
方法接受是一个参数列表。
apply()
用法:
functionName.apply(thisValue, parameter1, parameter2, ...);
所有的参数都是非必须的,请根据实际的参数/方法的定义传递参数。
在 JavaScript 中,所有函数都属于一个对象。如果一个函数看起来不属于一个对象,那么它属于全局对象。
this 关键字
在函数定义中, this
指的是函数的“所有者”。
下面的示例创建一个具有 2 个属性和一个方法的对象。
const person = {
firstName: "John",
lastName: "Doe",
fullName: function () {
return this.firstName + " " + this.lastName;
},
};
// 返回 "John Doe":
person.fullName();
在上面的示例中, this
是拥有 fullName
函数的 person
对象。也就是说, this.firstName
代表 person
对象的 firstName
属性。
! 提示: 在 JS this 关键字阅读更多关于 this
的信息。
JavaScript apply() 方法
apply()
方法是 Function 对象的一个方法,所有的函数/方法都可以通过 apply 调用。
使用 apply()
,可以将方法中的 this
由一个对象改为另一个对象。
此示例实现了 person
的 fullName
方法中传入 person1
的值:
const person = {
fullName: function () {
return this.firstName + " " + this.lastName;
},
};
const person1 = {
firstName: "John",
lastName: "Doe",
};
const person2 = {
firstName: "Mary",
lastName: "Doe",
};
// 返回 "John Doe":
person.fullName.apply(person1);
此示例实现了 person
的 fullName
方法中传入 person2
的值:
const person = {
fullName: function () {
return this.firstName + " " + this.lastName;
},
};
const person1 = {
firstName: "John",
lastName: "Doe",
};
const person2 = {
firstName: "Mary",
lastName: "Doe",
};
// 返回 "Mary Doe"
person.fullName.apply(person2);
apply() 方法的参数
apply()
方法除了第一个参数接受 this 的值之外,还接受一个包含多个参数的数组。
apply()
方法可以接受参数:
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"]);
在数组上模拟 Max 方法
您可以使用以下 Math.max()
方法找到最大的数字(在数字列表中):
Math.max(1, 2, 3); // 返回 3
由于 Math.max()
方法不支持数组参数,我们可以使用 apply()
传递一个数组。
Math.max.apply(null, [1, 2, 3]); // 返回 3
第一个参数 (null) 无关紧要。Math.max()
方法中并没有用到 this
,因此可以随便传值。
下面的示例都给出相同的结果:
Math.max.apply(Math, [1, 2, 3]); // 返回 3
Math.max.apply(" ", [1, 2, 3]); // 返回 3
Math.max.apply(0, [1, 2, 3]); // 返回 3