tomsseisums
tomsseisums

Reputation: 13357

Current object property as value in same object different property

Sorry for such a random title, but have no idea how to explain it better. And therefore, no idea if this is a duplicate question or not.

So, when declaring a new object, I'm looking to calculate the giga value:

var myObject = {
    super : 1,
    mega : 5,
    uber : 100,
    giga : this.super + this.mega + this.uber // super + mega + uber doesn't cut it either..
};

But this doesn't work, so, any ways of doing this while declaring, or not possible?

Hope I've made myself clear and thanks in advance!

Upvotes: 1

Views: 2323

Answers (3)

Raynos
Raynos

Reputation: 169373

var myObject = {
    super : 1,
    mega : 5,
    uber : 100
};
myObject.giga = myObject.super + myObject.mega + myObject.uber;

Upvotes: 0

georg
georg

Reputation: 214949

In Javascript 1.5 you can use the get keyword to define a getter

var obj = {
    super : 1,
    mega : 5,
    uber : 100,
    get giga() {
        return this.super + this.mega + this.uber;
    }
};

alert(obj.giga) // 106

more on this http://robertnyman.com/2009/05/28/getters-and-setters-with-javascript-code-samples-and-demos/

Upvotes: 6

Esailija
Esailija

Reputation: 140210

I assume you have a really good reason for the need to do this inline, otherwise such trickery is not really a good idea.

Here is what I came up with:

var myObject = (function(){
    this.giga = this.super + this.mega + this.uber;
    return this;
}).call({
    super : 1,
    mega : 5,
    uber : 100
});

Upvotes: 4

Related Questions