开发者

Reuse object within another object

I have an object that contains another object with translations. It looks like this:

var parent 开发者_C百科= { //parent object with a bunch of stuff in it
    countryAlerts:{ //area for country alerts
        "USA":{ //country
            en:"FAST", //alert text in English
            es:"RAPIDO" //alert text in Spanish
        },
        "Japan":{
            en:"FAST",
            es:"RAPIDO"
        }
    }
}

I would like to do something like this:

var parent = {
    countryAlerts:{
        "USA":fast,
        "Japan":fast
    }
}

var fast = {
    en:"FAST",
    es:"RAPIDO"
}

I can't seem to get it to work though. I would like to refer to the object like this: parent.countryAlerts.USA.LANGUAGE.

Any help is appreciated.

Thanks!


Yes that is possible, you just have to define fast first:

var fast = {
    en: "FAST",
    es: "RAPIDO"
};
var parent = {
    countryAlerts: {
        "USA" : fast,
        "Japan" : fast
    }
};

var lang = "en";

alert(parent.countryAlerts.USA[lang]); // "FAST"

Note the use of the square bracket notation for accessing an object's members by a variable name.

Edit: In response to the comment:

Ahh, that was silly. Thanks! I have another question now. Let's say I want to store fast in the parent object.

So you mean, like this (pseudo-code)?

var parent = {
    fast : {
        en : "FAST",
        es : "RAPIDO"
    },
    countryAlerts : 
        "USA" : fast    // ** magic here
        "Japan" : fast  // **
    }
};

In short, you can't do it in one statement like that. Your best bet would be to move it to multiple statements.

var parent = {
    fast : {
        en : "FAST",
        es : "RAPIDO"
    }
};
parent.countryAlerts = {
    "USA" : parent.fast,
    "Japan" : parent.fast
};


For your follow-up:

var parent = new (function()
{
    var fast = {
      en: "FAST",
      es: "RAPIDO"
    };

    this.countryAlerts = {
        "USA" : fast,
        "Japan" : fast
    };
})();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜