JavaScript 函數 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() 方法的第一個參數不是對象,則它將成為被調用函數的所有者(對象)。在“非嚴格”模式下,它成為全局對象。