指某东西的用途apply
与函数上下文相关(this
关键字)和参数传递。
首先,我想你应该知道在什么情况下this
关键字是隐含地 set:
1- 当函数作为方法调用时(该函数作为对象的成员调用):
obj.method(); // 'this' inside method will refer to obj
2- 正常的函数调用:
myFunction(); // 'this' inside the function will refer to the Global object
// or
(function () {})();
3- 当new
使用运算符:
var obj = new MyObj(); // this will refer to a newly created object.
这是当apply
and call
来吧,那些方法让你设置明确地调用函数时的上下文,例如:
function test(a) {
alert(this + a);
}
test.call('Hello', ' world!');
在上面的代码中,当test
函数被称为设置this
关键字到字符串 ('Hello'
),并通过a
争论 (' world.'
).
Both, call
and apply
更改执行函数的上下文(this
关键字)在被调用函数内部,但是不同之处他们之间是apply
,您可以发送一个数组或类似数组的对象作为要执行的函数的参数,这非常有用,例如:
function sum() {
var result = 0;
for (var i = 0; i < arguments.length; i++) {
result += arguments[i];
}
return result;
}
var args = [1,2,3];
sum.apply(null, args); // will return 6
这可以避免一些非常hacky的事情,bad(和常见的)eval
调用如下:
eval('sum(' + args.join() +')');
另一个例子,Math.max
and Math.min
方法,这些方法可以接收任意数量的参数,例如:
var max = Math.max(2,4,6,8); // 8
但是如果你有一个数字数组怎么办?
var numbers = [2,4,6,8];
numbers.push(10);
var max = Math.max.apply(null, numbers); // 10
还要注意,当null
or undefined
被用作this
与争论call
or apply
, the this
object 将引用 Global 对象(类似于情况 #2,正常函数调用)。
For the Math.max
例如,上下文并不真正相关,因为它们就像"static"方法,将this
关键字未在内部使用...