This question already has an answer here:
I'm looking for a trick about this. I know how to call a dynamic, arbitrary function in Javascript, passing specific parameters, something like this:
function mainfunc (func, par1, par2){
window[func](par1, par2);
}
function calledfunc(par1, par2){
// Do stuff here
}
mainfunc('calledfunc','hello','bye');
I know how to pass optional, unlimited parameters using arguments[] collection inside mainfunc, but, I can't figure how to send an arbitrary number of parameters to mainfunc to be sent to calledfunc dynamically; how can I accomplish something like this, but with any number of optional arguments (not using that ugly if-else)? :
function mainfunc (func){
if(arguments.length == 3)
window[func](arguments[1], arguments[2]);
elseif(arguments.length == 4)
window[func](arguments[1], arguments[2], arguments[3]);
elseif(arguments.length == 5)
window[func](arguments[1], arguments[2], arguments[3], arguments[4]);
}
function calledfunc1(par1, par2){
// Do stuff here
}
function calledfunc2(par1, par2, par3){
// Do stuff here
}
mainfunc('calledfunc1','hello','bye');
mainfunc('calledfunc2','hello','bye','goodbye');
You could use
.apply()
You need to specify a
this
... I guess you could use thethis
withinmainfunc
.Here's what you need:
The first argument is used as the function name and all of the remaining ones are used as arguments to the called function...
We're able to use the
shift
method to return and then delete the first value from the arguments array. Note that we've called it from the Array prototype since, strictly speaking, 'arguments' is not a real array and so doesn't inherit theshift
method like a regular array would.You can also call the shift method like this:
Your code only works for global functions, ie. members of the
window
object. To use it with arbitrary functions, pass the function itself instead of its name as a string:Now I'm using this:
Couldn't you just pass the
arguments
array along?