Reputation: 48565
I'm trying to execute a function from a string along with an array which should be treated as multiple arguments.
Example:
var app = {
bar : function(val1, val2, val4){
console.log(val1+val2+val3);
}
};
fn_name = "bar";
fn_args = ['one', 'two', 'three'];
app[fn_name](fn_args);
The issue with this code is that the fn_args
is being passed as one single argument rather than spread as separate arguments, Is there a work around? i still want to pass fn_name
and fn_args
dynamically.
Upvotes: 1
Views: 96
Reputation: 6572
Use function.apply()
.
app[fn_name].apply(app, fn_args);
The first arguument is the context (this
) inside the function, and the second is the array whose items should be passed as arguments.
Upvotes: 1
Reputation: 23770
Use the apply
method:
app[fn_name].apply(app, fn_args);
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/apply
Upvotes: 2