3

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?

Amy
  • 7,388
  • 2
  • 20
  • 31
sidlejinks
  • 709
  • 1
  • 9
  • 25

1 Answers1

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

Amy
  • 7,388
  • 2
  • 20
  • 31