为什么我不能通过引用内部函数在Javascript中创建对象?

时间:2013-03-27 18:18:36

标签: javascript

我正在尝试在Javascript中执行某种多态对象,其中我有一个对象'types'的映射,每个都有自己的属性和函数,我可以调用它。

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

这是我的代码:

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函数的引用!

我想避免像动作一样愚蠢:function(count):this.kick(count);即使它不起作用 - 我想要直接引用而不必重新键入parms

1 个答案:

答案 0 :(得分: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);

FIDDLE

相关问题