0

我正在尝试在 Javascript 中做一些面向多态对象的事情,其中​​我有一个对象“类型”的映射,每个对象都有自己可以调用的属性和函数。

虽然属性工作正常,但功能却没有,我不明白为什么。在 Firefox 中,我收到错误:TypeError: this.functionmap[type].action is not a function

这是我的代码:

var object = {
    flapWings : function(count) { alert("I am flapping my wings "+count+" times"); },
    kick : function(count) { alert("I am kicking my legs "+count+" times"); },
    functionmap : {
        "bird" : { label : "Bird", action : this.flapWings },
        "horse" : { label : "Horse", action : this.kick }
    },
    doAction : function (type, count) {
         alert("I am a "+this.functionmap[type].label);
         this.functionmap[type].action(count);
    }
};

object.doAction("horse", 5);

这是 JSFiddle 示例:

http://jsfiddle.net/JKvyP/

我只是不明白为什么: action : this.kick 没有得到对在它上面创建的 kick 函数的引用!

我想避免一些愚蠢的事情,比如 action : function(count) : this.kick(count); 即使那也不起作用-我想要直接引用而不必重新输入参数

4

1 回答 1

1

您不能神奇地将参数传递给刚刚引用的函数,因此您需要一些匿名函数,并直接在该范围内引用对象等:

var object = {
    flapWings : function(count) { 
        alert("I am flapping my wings "+count+" times"); 
    },
    kick : function(count) {
        alert("I am kicking my legs "+count+" times"); 
    },
    functionmap : {
         "bird" : { 
                   label : "Bird", 
                   action : function(param) {
                                object.flapWings(param);
                           }
                  },
        "horse" : { 
                   label : "Horse", 
                   action : function(param) {
                               object.kick(param);
                            }
                   }
    },
    doAction : function (type, count) {
         alert("I am a "+this.functionmap[type].label);
         this.functionmap[type].action(count);
    }
};

object.doAction("horse", 5);

小提琴

于 2013-03-27T18:28:11.893 回答