问题描述
我正在阅读O'Reilly的Javascript Web应用程序。在书中的不同点,作者使用了以下内容: instance.init.apply(instance,arguments);
这是否有意义?这不是完全一样的:
instance.init(arguments);
.call()和.apply()用于手动设置函数的执行上下文。为什么要在我打算使用原始执行上下文时使用它们?
关键是 arguments
是一个类似数组的对象。正在做...
instance.init(arguments);
...传递一个参数,它是一个包含某些参数的类似数组的对象。另一方面,这样做...
instance.init.apply(instance,arguments);
...会传递类似数组的对象作为单独的参数。确实,设置 instance
是没用的,因为你已经写了它,但是如果使用 .apply
,你只需要设置这个
值。
差异的一个简单例子:
函数日志(a,b,c){
console.log(a,b,c);
函数log2(){
log.apply(null,arguments); //这个值在这里没有意义,
//它是关于`arguments`
}
函数log3(){
log(arguments);
}
log(1,2,3); //日志:1,2,3
log2(1,2,3); //日志:1,2,3
log3(1,2,3); // logs:< Arguments>,undefined,undefined
//其中< Arguments>包含值1,2,3
I'm reading Javascript Web Applications, from O'Reilly. At various points in the book, the author uses something along the following:
instance.init.apply(instance, arguments);
Does this make any sense? Isn't this exactly the same as:
instance.init(arguments);
.call() and .apply() are used to manually set the execution context of a function. Why should I use them when I'm intending to use the original execution context anyway?
The point is that arguments
is an array-like object. Doing ...
instance.init(arguments);
... passes one argument, which is an array-like object containing certain arguments. On the other hand, doing ...
instance.init.apply(instance, arguments);
... will pass the array-like object as separate arguments. It is true that setting instance
is kind of useless because you already wrote it, but if using .apply
you simply need to set the this
value as well.
A quick example of the difference:
function log(a, b, c) {
console.log(a, b, c);
}
function log2() {
log.apply(null, arguments); // `this` value is not meaningful here,
// it's about `arguments`
}
function log3() {
log(arguments);
}
log(1, 2, 3); // logs: 1, 2, 3
log2(1, 2, 3); // logs: 1, 2, 3
log3(1, 2, 3); // logs: <Arguments>, undefined, undefined
// where <Arguments> contains the values 1, 2, 3
这篇关于使用.apply()并将相同的实例作为上下文传递是否合理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!