0

I have a pre-process function, here's an example function

function preprocess (msg, fct) {
   alert(msg);
   fct(???);
}

I need to execute the function fct in the preprocess function, but fct not always has the same number of parameters. I am not a pro in javascript but I think there are 2 ways to achieve that :

  1. explicit call with an object

    function preprocess (msg, fct, obj) { ... }
    

usage : preprocess ('hello', myfct, {firstparam: 'foo', secondparam: 'bar'});

  1. using the argument inner property of the function

anyways i might have the theory, i am not able to code both the case above. Is it possible to achieve what I need using both the ways ? if yes, could you provide a minimum example of each to show me the way ?

vdegenne
  • 12,272
  • 14
  • 80
  • 106

1 Answers1

2

You can pass the arguments at the end in variadic form, and use the arguments object to get what you need:

function preprocess (msg, fct /*, ...as*/) {
  var as = [].slice.call(arguments, 2);
  alert(msg);
  fct.apply(this, as);
}

preprocess(msg, fct, a, b, c); // fct(a, b, c)
elclanrs
  • 92,861
  • 21
  • 134
  • 171