1

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!

tomsseisums
  • 13,168
  • 19
  • 83
  • 145
  • 1
    possible duplicate of [Self-references in object literal declarations](http://stackoverflow.com/questions/4616202/self-references-in-object-literal-declarations) – Felix Kling Nov 07 '11 at 13:07

3 Answers3

6

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/

georg
  • 211,518
  • 52
  • 313
  • 390
  • 1
    That will completely fall over on non-ES5 browsers. Please use `Object.defineProperty` to define getter/setters – Raynos Nov 07 '11 at 13:14
  • There is no specification whether I'm interested in ES5 or ES4 or ESx, I see no reason for the downvote. In fact, this is the cleanest answer so far. – tomsseisums Nov 07 '11 at 13:44
4

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
});
Esailija
  • 138,174
  • 23
  • 272
  • 326
0
var myObject = {
    super : 1,
    mega : 5,
    uber : 100
};
myObject.giga = myObject.super + myObject.mega + myObject.uber;
Raynos
  • 166,823
  • 56
  • 351
  • 396