您的位置:首页 > 移动开发

Javascript学习笔记: Function::apply 方法

2004-12-17 11:54 716 查看
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的文章,顺便学习一下英语,呵呵,就翻译出来,第一次翻译文章,如果有什么不对的地方,请多指教
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: