METHOD: Function::apply
--------------------------------------------------------------------------------
Function.apply(thisObj[, argArray])
apply 方法允許調用某一個對象的一個方法,並且用指定的一個對象替換當前的對象.
參數
thisObj
可選項。將被用作當前對象的對象。
argArray
可選項。將被傳遞給該函數的參數數組。
The apply method allows you to call a function and specify what the keyword this will refer to within the context of that function. The thisArg argument should be an object. Within the context of the function being called, this will refer to thisArg. The second argument to the apply method is an array. The elements of this array will be passed as the arguments to the function being called. The argArray parameter can be either an array literal or the deprecated arguments property of a function.
The apply method can be used to simulate object inheritance as in the following example. We first define the constructor for an object called Car which has three properties. Then the constructor for a second object called RentalCar is defined. RentalCar will inherit the properties of Car and add one additional property of its own - carNo. The RentalCar constructor uses the apply method to call the Car constructor, passing itself as thisArg. Therefore, inside the Car function, the keyword this actually refers to the RentalCar object being constructed, and not a new Car object. By this means,the RentalCar object inherits the properties from the Car object.
以下的例子用 apply 方法類比一個對象的繼承.第一先定義一個Car對象的構造方法,有三個屬性.第二再定義一個RentalCar對象的構造方法,RentalCar將繼承Car的屬性並加上一個自己的屬性carNo. RentalCar構造方法使用 apply 方法去調用Car的構造方法,把自身當作thisArg參數傳遞過去.因此,在Car函數的內部,關鍵字 this 實際上已經被 RentalCar 對象代替,並不是一個新的 Car 對象.通過這個方法,RentalCar對象從Car對象繼承了它的屬性.
Code:
function Car(make, model, year)
{
this.make = make;
this.model = model;
this.year = year;
}
function RentalCar(carNo, make, model, year)
{
this.carNo = carNo;
Car.apply(this, new Array(make, model, year));
}
myCar = new RentalCar(2134,"Ford","Mustang",1998);
document.write("Your car is a " + myCar.year + " " + myCar.make + " " + myCar.model + ".") ;
Output:
Your car is a 1998 Ford Mustang.
NOTE: The apply method is very similar to the call method and only differs in that, up until now, you could use the deprecated arguments array as one of its parameters.
NOTE: apply 方法非常像 call 的方法,唯一的區別是 apply 方法傳遞的參數是 arguments 或 Array 對象
ps:網上找的一篇介紹關於apply的文章,順便學習一下英語,呵呵,就翻譯出來,第一次翻譯文章,如果有什麼不對的地方,請多指教