Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic function call (apply)

Tags:

javascript

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 || []);
        }
    }

};
like image 917
Louis W Avatar asked Feb 15 '26 22:02

Louis W


2 Answers

There are (at least) two problems with your use of apply here.

  1. It is a method of a function object, and you seem to be calling it on strings

  2. 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.

like image 187
Ian Clelland Avatar answered Feb 18 '26 12:02

Ian Clelland


The problem is that do.action is a string, not a function. You could change your code in one of two ways.

  1. 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.

  2. Resolve the string back to the actual property:

    this[do.action].apply(...)
    
like image 41
nickf Avatar answered Feb 18 '26 10:02

nickf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!