What's the difference between f(arguments) to f.apply(this,arguments)?

六眼飞鱼酱① 提交于 2019-12-10 19:03:30

问题


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:


  1. f(arguments) just calls f and passes an Array-like object (containing arguments) to it, this is not what you'd want.

  2. 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.

  3. f.apply(this, arguments) would call f and passes each argument in arguments 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/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


来源:https://stackoverflow.com/questions/23254225/whats-the-difference-between-farguments-to-f-applythis-arguments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!