简体   繁体   中英

accessing methods of an object within an array

I have an array which I'm adding objects to dynamically like so

var _plugins = [];

this.registerPlugin = function(plugin){

    _plugins.push(plugin);
    plugin.onInit()
}, 

This is all within a class and I am trying to use a method like this which should run the method passed in to meth

this.runPluginMethod = function(meth, call_obj){
    for (x in _plugins){
        x[meth](call_obj)
    }
}

The Objects I am adding to the _plugins array are created like this

var ourPlugin = Object.create(babblevoicePlugin);

Object.defineProperty(ourPlugin, 'onInit', {value : function() 
{
    console.log('this is from reflex oninit')

}});

When I try running mianClass.runPluginMethod('onInit', 'a') It does nothing, doesn't run console.log like it should to my mind.

Can anyone help? am I doing something wrong? is this possible?

I think the problem is here:

this.runPluginMethod = function(meth, call_obj){
    for (x in _plugins){
        x[meth](call_obj)
    }
}

You're trying to access a property of a key instead of the object you're looking for. Changing it to the following should work.

this.runPluginMethod = function(meth, call_obj){
    for (x in _plugins){
        _plugins[x][meth](call_obj)
    }
}

EDIT

As another example, check the output of the following in a js console:

x = ['a','b','c'];
for (i in x){ console.log(i, x[i]) };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM