开发者

Dynamic function call (apply)

开发者 https://www.devze.com 2022-12-13 22:23 出处:网络
I am trying to dynamica开发者_如何学Golly 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 sho

I am trying to dynamica开发者_如何学Golly 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.

  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.


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(...)
    
0

精彩评论

暂无评论...
验证码 换一张
取 消