object * name *没有方法*方法名*

时间:2011-12-01 22:39:32

标签: javascript

我有两个对象:commandtopic

topic有一个方法actions,可以从command调用。

调用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;
    }
}

1 个答案:

答案 0 :(得分:0)

实际上你的问题主要在那里:

  

其值是要调用的字符串'topic'...

您想要的是访问包含主题{}对象的Object的'topic'属性。

因此你想要:

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

包含对象(如果您没有将主题附加到某些内容)将在浏览器环境中window或在NodeJS中global

相关问题