2011-12-20 97 views
0

我在JavaScript中做一個國際化的物體,像下面在我的JavaScript文件來管理的語言功能的JavaScript調用字符串作爲

i18n = { 

     currentCulture: 'pt_PT', 

     pt_PT : { 
      message_key : "text in portuguese" 
     }, 
     en_US: { 
      message_key : "text in english", 
     }, 

     /** 
     * translate 
     */ 
     __ : function(key,culture){ 
       return this.culture.key; 
     }, 


     /** 
     * returns the active user culture 
     */ 
     getUserCulture : function(){ 
      return this.currentCulture; 
     }, 


     /** 
     * sets the current culture 
     */ 
     setCulture : function(culture){ 
      this.currentCulture = culture; 
     } 
} 

我需要的基礎上,重點和文化PARAMS返回正確的消息翻譯功能。 問題是,在行返回this.culture.key; javascript試圖在i18n對象中找到「文化」禮節。 我如何使它調用,例如this.pt_PT.message_key?

感謝您的幫助。

謝謝大家誰發佈的解決方案。我只能接受一個anwser,所以我接受第一個。

回答

3

使用bracket notation。假設culture'pt_PT'key'message_key'

return this[culture][key]; 
+0

謝謝。它工作正常。 – brpaz 2011-12-21 09:19:04

3

替換:

this.culture.key 

有:

this[culture][key] 
1

JavaScript對象are associative arrays,您可以使用數組語法查找屬性:

return this[culture][key];

+1

它不像「括號表示法」那樣稱爲「數組語法」。 – 2011-12-20 17:14:17