javascript 将字符串作为函数调用

发布于 2024-12-22 04:14:23 字数 973 浏览 2 评论 0原文

我在 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;
        }
}

我需要根据翻译函数的键和区域性参数返回正确的消息。 问题在于,在 return this.culture.key; 行中,javascript 试图在 i18n 对象中找到“文化”属性。 我怎样才能让它调用,例如 this.pt_PT.message_key?

感谢您的帮助。

感谢所有发布解决方案的人。我只能接受一个答案,所以我接受第一个。

I have made an i18n object in javascript like the following to manage the languages in my javascript files

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;
        }
}

I need to return the correct message based on the key and culture params of the translate function.
The problem is that in the line return this.culture.key; javascript is trying to find a "culture" propriety in the i18n object.
How can i make it call, for example this.pt_PT.message_key?

Thanks for your help.

Thanks everyone who posted the solution. I can only accepted one anwser so i accept the first one.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

相思故 2024-12-29 04:14:23

使用括号表示法。假设 culture'pt_PT'key'message_key'

return this[culture][key];

Use bracket notation. Assuming culture is 'pt_PT' and key is 'message_key':

return this[culture][key];
赠我空喜 2024-12-29 04:14:23

替换:

this.culture.key

为:

this[culture][key]

Replace:

this.culture.key

with:

this[culture][key]
青巷忧颜 2024-12-29 04:14:23

Javascript 对象是关联数组,您可以使用数组语法来查找属性:

返回这个[文化][键];

Javascript objects are associative arrays, and you can use array syntax to look up properties:

return this[culture][key];

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文