简体   繁体   English

访问数组中对象的方法

[英]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 这都在一个类中,我正在尝试使用类似这样的方法,该方法应该运行传递给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 我要添加到_plugins数组的对象是这样创建的

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. 当我尝试运行mianClass.runPluginMethod('onInit', 'a')它什么也没做,没有像我想的那样运行console.log。

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: 再举一个例子,在js控制台中检查以下内容的输出:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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