I want to pass a varying number of argument to varying functions. I set up this basic test:
function overview(arg1, arg2, arg3) {
console.info('arg1 is ' + arg1);
console.info('arg2 is ' + arg2);
console.info('arg3 is ' + arg3);
}
function modules(method, args) {
this[method].apply(null, args);
}
modules('overview', new Array('test1', 'test2'));
So, I use 'apply' to pass an array with arguments via the 'modules' function to the 'overview' function. This works fine, except for the this[method]
part. I read about this in this Q&A: Calling dynamic function with dynamic parameters in Javascript and it seems marvelous. However, I keep getting 'TypeError' errors and I can't figure out how to resolve this.
Of course, I could use a switch
within the modules function to call the correct method, but that is unnecessary bulk (hopefully!). I've made a JSFiddle to 'fiddle' with: http://jsfiddle.net/QFpRc/. Hope anyone can solve and/or explain this.