Function::apply 方法

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的文章,顺便学习一下英语,呵呵,就翻译出来,第一次翻译文章,如果有什么不对的地方,请多指教

原帖地址:http://blog.csdn.net/cinnxu/archive/2004/12/17/219503.aspx

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值