2013-03-27 75 views
0

我正在嘗試做一些類似Javascript的多態對象,我有一個對象'類型'的映射,每個對象都有自己的屬性和函數,我可以調用它們。爲什麼不能用Javascript創建對象並引用內部函數?

雖然屬性正常工作的功能不,我不明白爲什麼。在Firefox中我得到的錯誤:類型錯誤:this.functionmap【類型】.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/

我只是不明白爲什麼: 行動:this.kick沒有得到正確的上面創建的踢功能的引用!我想避免像行動一樣愚蠢的東西:function(count):this.kick(count);即使這不起作用 - 我想直接引用,而不必重新鍵入參數

+1

http://stackoverflow.com/questions/4616202/self-references-in-object-literal-declarations/10766107#10766107 – 2013-03-27 18:22:50

+2

因爲在你的榜樣'這是指'馬'引用的對象? – Daedalus 2013-03-27 18:22:50

回答

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

+0

謝謝,我想我現在明白爲什麼我的嘗試不起作用。仍然有點消化它... :) – Trant 2013-03-27 18:42:14

相關問題