f(arguments)与f.apply(this,arguments)之间的区别是什么? [英] What's the difference between f(arguments) to f.apply(this,arguments)?
问题描述
我很久没学过JavaScript了,现在我正在尝试实现Decorator模式:
I have not been studying JavaScript for a long time and now I'm trying to implement the Decorator pattern:
function wrap(f, before, after){
return function(){
return before + f(arguments) + after;
}
}
我想知道的是,如果我们更换 f(参数)
到 f.apply(this,arguments)
输出没有明显差异。
你能否澄清哪个案例更可取?为什么?
What I'm wondering about is that if we replace f(arguments)
to f.apply(this,arguments)
there is no obvious difference in output.
Could you please clarify which case is preferable and why?
UPD:
我想我已经理解了什么是瓶颈:)
如果我们用上述代码装饰函数而没有参数,一切都会好的。但是如果我们有参数,我们将不得不枚举它们,如 arguments [0],arguments [1]
等。我是对的吗?
推荐答案
-
f(参数)
只需调用f
并传递一个类似 Array 的对象(包含参数),这是不你想要的。
f(arguments)
just callsf
and passes an Array-like object (containing arguments) to it, this is not what you'd want.
f.call(this,arguments [0],arguments [1],..)
会要求你列出每个参数都出来,它与 f(arguments [0],arguments [1],..)
几乎相同,减去函数上下文。
f.call(this, arguments[0], arguments[1], ..)
would require you to list every argument out and it's pretty much the same as f(arguments[0], arguments[1], ..)
, minus the function context.
f.apply(this,arguments)
将调用 f
并且将 arguments
中的每个参数作为实际参数传递。
f.apply(this, arguments)
would call f
and passes each argument in arguments
as actual arguments.
方法如果你想要实现一个包装器函数而不必考虑传递给 f
的参数,你会想要#3。
Method #3 is what you'd want if you're trying to implement a wrapper function and not have to consider what arguments are being passed into f
.
了解有关函数方法的更多信息:
Learn more about methods for Function:
-
call()
: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/致电 -
apply()
: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply -
arguments
: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/arguments
call()
: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/callapply()
: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/applyarguments
: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/arguments
这篇关于f(arguments)与f.apply(this,arguments)之间的区别是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!