I am writing a way to store method calls into an object:
var action = {'method':'foo', 'params': [1,'bob',45]}
I have my methods:
function foo(order, name, size);
function bar(input);
function baz(name, length, time, debug);
etc
When given an action I wish to automatically call the function associated with it:
var fn = window[action.method]
if(typeof fn === 'function')
{
fn(//blah)
}
The problem is, the action object has a list of parameters, but my functions take multiple parameters. How do I accomplish this?
Use
.apply:This calls
fn, but uses the first argument to set thethisvalue offn, and uses the individual members of the second argument (theaction.paramsarray) to populate the arguments of the call as individual arguments.I’d note that since you’re doing:
that you actually have the method name as a string: