brpaz
brpaz

Reputation: 3658

javascript invoke string as a function

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.

Upvotes: 0

Views: 161

Answers (3)

moonshadow
moonshadow

Reputation: 89115

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

return this[culture][key];

Upvotes: 1

Joe
Joe

Reputation: 82624

Replace:

this.culture.key

with:

this[culture][key]

Upvotes: 3

Matt Ball
Matt Ball

Reputation: 359966

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

return this[culture][key];

Upvotes: 3

Related Questions