很久没有学习JavaScript了,现在正在尝试实现Decorator模式:
function wrap(f, before, after){
return function(){
return before + f(arguments) + after;
}
}
我想知道的是,如果我们将 f(arguments)
替换为 f.apply(this,arguments)
,则输出没有明显差异。
您能否说明哪种情况更可取,为什么?
更新:
我想我已经明白瓶颈是什么了:)
如果我们用前面提到的不带参数的代码装饰函数,一切都会好起来的。但是如果我们有参数,我们将不得不像 arguments[0],arguments[1]
等那样枚举它们。我说得对吗?
最佳答案
f(arguments)
只需调用f
并将类似数组的对象(包含参数)传递给它,这不是您想要的。f.call(this, arguments[0], arguments[1], ..)
将要求您列出每个参数,它与f(arguments[0], arguments[1], ..)
几乎相同, 减去函数上下文。f.apply(this, arguments)
会调用f
并在arguments
中传递每个参数作为实参。
如果您尝试实现一个包装函数而不必考虑将哪些参数传递给f
,那么方法#3 就是您想要的。 .
了解有关 Function 方法的更多信息:
-
call()
: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call -
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
关于javascript - f(arguments) 和 f.apply(this,arguments) 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23254225/