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!
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!
Share Improve this question edited Nov 7, 2011 at 12:58 tomsseisums asked Nov 7, 2011 at 12:50 tomsseisumstomsseisums 13.4k20 gold badges88 silver badges148 bronze badges 1- 1 possible duplicate of Self-references in object literal declarations – Felix Kling Commented Nov 7, 2011 at 13:07
3 Answers
Reset to default 6In 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./2009/05/28/getters-and-setters-with-javascript-code-samples-and-demos/
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
});
var myObject = {
super : 1,
mega : 5,
uber : 100
};
myObject.giga = myObject.super + myObject.mega + myObject.uber;