Accessing previous values inside an object during declaration
Possible duplicate:
Self-promotions in object literal declarations
var obj = {
value: 10,
value2: value + 2
};
How can i do this? (Assuming it's possible)
I use a lot of jQuery $.extend
to add more properties that rely on previous added values; so changing a few values automatically adjusts the rest.
+3
source to share
2 answers
You cannot do this in a declaration, but you can always make a function. The following values will always return a value of 2 greater than the value stored in the value:
var obj = {
value: 10,
getValue2: function(){ return this.value + 2; }
};
If you don't want value2 to change along with the value, you can declare a placeholder variable and declare an object using this:
var placeholder = 10;
var obj = {
value: placeholder,
value2: placeholder + 2
};
+4
source to share