function.apply(thisArg[, argsArray])
Core JavaScript 1.5 Reference:Global Objects:Function:apply - MDC
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.
var result = function.apply(thisArg[, argsArray]);
thisArg
Determines the value of this inside fun. If thisArg is null or undefined, this will be the global object. Otherwise, this will be equal to Object(thisArg) (which is thisArg if thisArg is already an object, or a String, Boolean, or Number if thisArg is a primitive value of the corresponding type). Therefore, it is always true that typeof this == "object" when the function executes.
argsArray
An argument array for the object, specifying the arguments with which fun should be called, or null or undefined if no arguments should be provided to the function.
DevGuru JavaScript METHOD: Function::apply
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.
unction 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 + ".")
JavaScript 1.3 Overview, Part II: The call Method - Doc JavaScript
JavaScript 1.3 Overview, Part II: The apply Method - Doc JavaScript
沒有留言:
張貼留言