访问数组中对象的方法

时间:2022-01-10 15:16:00

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?

有人可以帮忙吗?难道我做错了什么?这可能吗?

1 个解决方案

#1


1  

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

#1


1  

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