Calling dynamic function with dynamic number of parameters

ARemesal picture ARemesal · Mar 24, 2009 · Viewed 218.3k times · Source

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 the 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 ifelse)?

function mainfunc(func){
    if(arguments.length == 3)
        window[func](arguments[1], arguments[2]);
    else if(arguments.length == 4)
        window[func](arguments[1], arguments[2], arguments[3]);
    else if(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');

Answer

AnthonyWJones picture AnthonyWJones · Mar 24, 2009

Use the apply method of a function:-

function mainfunc (func){
    window[func].apply(null, Array.prototype.slice.call(arguments, 1));
} 

Edit: It occurs to me that this would be much more useful with a slight tweak:-

function mainfunc (func){
    this[func].apply(this, Array.prototype.slice.call(arguments, 1));
} 

This will work outside of the browser (this defaults to the global space). The use of call on mainfunc would also work:-

function target(a) {
    alert(a)
}

var o = {
    suffix: " World",
    target: function(s) { alert(s + this.suffix); }
};

mainfunc("target", "Hello");

mainfunc.call(o, "target", "Hello");