【问题标题】:accessing methods of an object within an array访问数组中对象的方法
【发布时间】:2014-03-06 15:27:20
【问题描述】:

我有一个数组,我正在像这样动态添加对象

var _plugins = [];

this.registerPlugin = function(plugin){

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

这一切都在一个类中,我正在尝试使用这样的方法,它应该运行传递给meth的方法

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

我添加到 _plugins 数组的对象是这样创建的

var ourPlugin = Object.create(babblevoicePlugin);

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

}});

当我尝试运行 mianClass.runPluginMethod('onInit', 'a') 时,它什么也没做,也没有像我想的那样运行 console.log。

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

【问题讨论】:

  • 尝试调试。当您运行 this.runPluginMethod 时,x[meth] 的结果是什么?
  • 我认为你使用的 for 错误应该是 _plugins[x] javascript foreach 之类的语法不适用于其他语言
  • 什么是this? mainClass 是什么?发布一个完整但最小的工作示例而不是一堆片段怎么样?
  • @Carlos487 是正确的,我使用了 for 语句错误,在更改此语句后调试到语句 plugins[x] Object {} _plugins[x]['oninit'] undefined _plugins[x] ['onInit'] function () { console.log('this is from reflex oninit') } _plugins[x]['onInit']() TypeError: Cannot call method 'log' of null
  • 你可以试试这个 (_plugins[x])['onInit'] 看看它是否是一个函数,其他语法是用于二维数组

标签: javascript arrays object methods


【解决方案1】:

我认为问题出在这里:

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

您正在尝试访问键的属性,而不是您要查找的对象。将其更改为以下内容应该可以工作。

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

编辑

作为另一个例子,在 js 控制台中检查以下输出:

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

【讨论】:

  • 感谢您的回复,我已将其更改为您的建议,最好不要我收到TypeError: Cannot call method 'log' of null 它怎么找不到控制台对象?
  • 你在哪里运行代码? Not all browsers have console.log.
  • 我在 Chrome 中运行它
  • 嗯。它可能与调用时函数的范围有关。你可以尝试用_plugins[x][meth](call_obj) 换取_plugins[x][meth].call(this, call_obj),看看你会得到什么?
  • 我做了你建议的改变,没有任何区别。
猜你喜欢
  • 1970-01-01
  • 2018-12-04
  • 1970-01-01
  • 2012-02-27
  • 2017-08-13
  • 1970-01-01
  • 2019-06-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多