2011-12-01 74 views
1

我有兩個對象:commandtopic對象*名稱*沒有方法*方法名稱*

topic有一個從command調用的方法actions

當調用topic.actions()時,沒有錯誤。

當我使用對象屬性command.taxonomy,其值是字符串'topic'打電話topic.actions(),拋出一個異常:"Object topic has no method actions"

爲什麼控制檯報告topic沒有方法actions

command = { 
    /*this is set when an html element is clicked by another function: 
     for this example, it equals the string 'topic'*/ 
    taxonomy : '', 

    //this is called when the same html element is clicked as above 
    taxonomy_actions: function(){ 
     this.taxonomy.actions(); 
    } 
} 

topic = { 
    actions:function(){ 
     //returns an array of valid commands for topic 
     this.commands.push('shortcuts'); 
     this.commands.push('action_list'); 
     this.commands['shortcuts'] = new Array(); 
     this.commands['action_list'] = new Array(); 

     for(x in this.aliases){ 
       this.commands.action_list.push(this.aliases[x]); 
       this.commands.shortcuts.push(x); 
     } 
     return this.commands; 
    } 
} 
+6

請把實際的調用代碼放在這裏 - 我不知道什麼「當我使用參數command.taxonomy的值是字符串'主題'來調用topic.actions()」的意思。 –

+5

那麼'taxonomy'是字符串''topic''?字符串沒有'actions()'方法。我想你想把'taxonomy'設置爲* object *'topic',而不是一個字符串。 –

+0

@火箭:好的建議,在我看來,是正確的。我收到的錯誤信息現在非常有用。我將實際的分類對象分配給了我的命令對象的一個​​屬性,並且我可以從分類對象中訪問我想要的屬性。 – kevtrout

回答

0

它實際上是主要存在於你的問題:

,它的值是字符串「主題」叫......

你想要的是訪問「話題'包含主題{}對象的對象的屬性。

因此你想:

taxonomy_actions: function(){ 
    containing_object[this.taxonomy].actions(); 
} 

包含的對象(如果你不重視的話題的東西)將在瀏覽器環境windowglobal中的NodeJS。