I am trying to dynamically call a function inside of an object. Found the apply function but not fully understanding it. Check out the code below, by triggering Test.checkQueue() it should in turn call showSomething "method". Thanks.
var Test = {
, queue : [{action:'showSomething', id:'1234'},{action:'showOther', id:'456'}]
, showSomething: function(what) {
alert(what);
}
, checkQueue : function() {
console.log('checkQueue');
console.log(this.queue);
if (this.queue.length) {
var do = this.queue.shift();
console.log(do);
// action.action(action.id);
do.action.apply(this, do.id || []);
}
}
};
There are (at least) two problems with your use of apply here.
It is a method of a function object, and you seem to be calling it on strings
It always takes an array as its second parameter -- you are passing in either a string or an empty array.
Try calling it like this:
Test[do.action].apply(this, do.id ? [do.id] : []);
Using Test[do.action] will access the actual function, rather than the string "showSomething" or "showOther", and do.id ? [do.id] : [] will always return an array.
The problem is that do.action is a string, not a function. You could change your code in one of two ways.
Instead of storing the name of the function in your queue, actually store the function:
queue : [ { action: this.showSomething ...
You might need to make sure that it has been defined first or something like that, though.
Resolve the string back to the actual property:
this[do.action].apply(...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With