簡體   English   中英

javascript將字符串作為函數

[英]javascript invoke string as a function

我已經在javascript中制作了一個i18n對象,如下所示,以管理我的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;
        }
}

我需要根據翻譯功能的鍵和文化參數返回正確的消息。 問題是在該行中返回this.culture.key;。 javascript試圖在i18n對象中找到“文化”專有性。 我如何調用它,例如this.pt_PT.message_key?

謝謝你的幫助。

感謝發布解決方案的所有人。 我只能接受一個答案,所以我接受第一個。

使用括號符號 假設culture'pt_PT'key'message_key'

return this[culture][key];

更換:

this.culture.key

與:

this[culture][key]

Javascript對象是關聯數組 ,您可以使用數組語法查找屬性:

return this[culture][key];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM