Search code examples
javascriptjqueryobjectproperties

Setting property value from other property value inside object


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.


Solution

  • You can declare your properties as functions

    var obj = {
      prop1:1,
      prop2:function(){
        return this.prop1 + 1;
      }
    }