Reputation: 159
Is there a way to set the value of a property within an object relative to another property within the same object?
For example:
var myObj = {
prop1 = 10,
prop2 = prop1 + 5
};
alert(myObj.prop2); //Alerts 15
Another example would be for when I create objects within an object aswell
var mainObj = {
obj1: {x: 100, y:100},
obj2: {x: obj1+10, y: obj1+10}
};
alert(mainObj.obj2.x); //Alerts 110
I want certain properties to stay relative to other properties in the same object, so that when I change one property, it will affect the other property.
Upvotes: 6
Views: 6120
Reputation: 33
The marked answer is a way around using a function instead of a property. The correct answer to the initial question is using the get
syntax.
The difference is shown in the following example:
var myObj = {
prop1 = 10,
get prop2(){this.prop1 + 5}
prop3 : function(){return this.prop1 + 5}
};
console.log(myObj.prop2); // Prints: 15
console.log(myObj.prop3()); // Prints: 15
Similar post/answer.
Upvotes: 3
Reputation: 3387
If you don't care about backwards compatibility with browsers that only support ECMAScript 3, you can use accessors (setters and getters) featured in ECMAScript 5:
var myObj = Object.create(null, {
prop1: {
writable: true,
configurable: true,
value: 10
}, prop2: {
get: function() {
return this.prop1 + 5;
}
}
});
myObj.prop1 // 10
myObj.prop2 // 15
myObj.prop1 = 20 // 20
myObj.prop2 // 25
myObj.prop2 = 6 // 6
myObj.prop2 // 25
See also the Object.defineProperty()
method, which allows you to add accessors to already existing objects.
Upvotes: 0
Reputation: 534
You can declare your properties as functions
var obj = {
prop1:1,
prop2:function(){
return this.prop1 + 1;
}
}
Upvotes: 8