ประกาศประกาศการเรียกใช้ฟังก์ชัน Apply
方法重用
通过 apply()
方法,您能够编写用于不同对象的方法。
JavaScript apply() 方法
apply()
方法与 call()
方法非常相似:
在本例中,person
的 fullName
方法被应用到 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()
ǰһǩǶǸöее÷()еö