问题
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;
}
}
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:
I suppose I have understood what is the bottleneck :)
If we decorate function with aforementioned code without arguments, everything will be ok. But if we have arguments we will have to enumerate them like arguments[0],arguments[1]
etc. Am I right?
回答1:
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], ..)
would require you to list every argument out and it's pretty much the same asf(arguments[0], arguments[1], ..)
, minus the function context.f.apply(this, arguments)
would callf
and passes each argument inarguments
as actual arguments.
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/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
来源:https://stackoverflow.com/questions/23254225/whats-the-difference-between-farguments-to-f-applythis-arguments