Calling dynamic function with dynamic number of parameters
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:
function dispatch(fn, args) {
fn = (typeof fn == "function") ? fn : window[fn]; // Allow fn to be a function object or the name of a global function
return fn.apply(this, args || []); // args is optional, use an empty array by default
}
function f1() {}
function f2() {
var f = function() {};
dispatch(f, [1, 2, 3]);
}
dispatch(f1, ["foobar"]);
dispatch("f1", ["foobar"]);
f2(); // calls inner-function "f" in "f2"
dispatch("f", [1, 2, 3]); // doesn't work since "f" is local in "f2"
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");