簡體   English   中英

訪問數組中對象的方法

[英]accessing methods of an object within an array

我有一個數組,我正在像這樣動態添加對象

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM