javascript apply vs call

8.6.4. The apply() and call() Methods

ECMAScript specifies two methods that are defined for all functions, call() and apply() . These methods allow you to invoke a function as if it were a method of some other object. The first argument to both call() and apply() is the object on which the function is to be invoked; this argument becomes the value of the this keyword within the body of the function. Any remaining arguments to call() are the values that are passed to the function that is invoked. For example, to pass two numbers to the function f() and invoke it as if it were a method of the object o , you could use code like this:

f.call(o, 1, 2);

 

This is similar to the following lines of code:

o.m = f;
o.m(1,2);
delete o.m;

 

The apply() method is like the call() method, except that the arguments to be passed to the function are specified as an array:

f.apply(o, [1,2]);

 

For example, to find the largest number in an array of numbers, you could use the apply() method to pass the elements of the array to the Math.max() function:

var biggest = Math.max.apply(null, array_of_numbers);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值