JavaScript Function apply()
方法重用
使用 apply()
方法,您可以编写一个可以用于不同对象的方法。
JavaScript apply() 方法
JavaScript apply()
方法与 call()
方法(上一章)类似。
在此示例中,person
的 fullName 方法被 应用 于 person1
示例
const person = {
fullName: function() {
return this.firstName + " " + this.lastName;
}
}
const person1 = {
firstName: "Mary",
lastName: "Doe"
}
// 这将返回 "Mary Doe"
person.fullName.apply(person1);
call() 和 apply() 之间的区别
区别在于:
call()
方法单独传递参数。
apply()
方法将参数作为 **数组** 传递。
如果您想使用数组而不是参数列表,apply()
方法非常方便。
带参数的 apply() 方法
apply()
方法接受数组形式的参数。
示例
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"]);
与 call()
方法比较
示例
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()
方法查找最大数字(数字列表中的最大值)。
由于 JavaScript **数组** 没有 max() 方法,因此您可以改用 Math.max()
方法。
第一个参数 (null) 无关紧要。在此示例中未使用。
这些示例将产生相同的结果
JavaScript 严格模式
在 JavaScript 严格模式下,如果 apply()
方法的第一个参数不是对象,它将成为调用函数的“所有者”(对象)。在“非严格”模式下,它将成为全局对象。