ประกาศประกาศการเรียกใช้ฟังก์ชัน Apply

方法重用

通过 apply() 方法,您能够编写用于不同对象的方法。

JavaScript apply() 方法

apply() 方法与 call() 方法非常相似:

在本例中,personfullName 方法被应用person1

ʵ

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

ʵ

call() 和 apply() 之间的区别

不同之处是:

call() 方法分别接受参数。

apply() 方法接受数组形式的参数。

如果要使用数组而不是参数列表,则 apply() 方法非常方便。

带参数的 apply() 方法

apply() 方法接受数组中的参数:

ʵ

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"]);

ʵ

call() 方法对比:

ʵ

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");

ʵ

бϵ max 方法

ʹ Math.max() ҵ(бе)ֵ

ʵ

Math.max(1,2,3);  // Ҳ 3

ʵ

JavaScript ʱû max() 方法 Math.max() 方法

ʵ

Math.max.apply(null, [1,2,3]); // Ҳ 3

ʵ

һ(null)Ҫ

ǰʾ

ʵ

Math.max.apply(Math, [1,2,3]); // Ҳ 3

ʵ

ʵ

Math.max.apply(" ", [1,2,3]); // Ҳ 3

ʵ

ʵ

Math.max.apply(0, [1,2,3]); // Ҳ 3

ʵ

JavaScript ˽ģʽ

JavaScript ˽ģʽ£ apply() ǰһǩǶ󣬾Ǹöее÷(󡢡)еö