6

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.

JimiiBee
  • 159
  • 4
  • 14
  • Not really, at least not like that, and why would you need to ? – adeneo Dec 13 '14 at 21:30
  • I was just wondering because It would make editing properties of some objects easier for my code – JimiiBee Dec 13 '14 at 21:35
  • There's functions and object.watch, none of them really do what you're trying to do, but functions, like below, is probably the easiest to add a property and return the result, but it's completely different from what you're doing. – adeneo Dec 13 '14 at 21:38
  • Well no, that way does work for what I want as it does define a property from another property. It's just not as simple as I'd hoped – JimiiBee Dec 13 '14 at 21:42
  • A more complete discussion of [self-referencing properties on this thread](https://stackoverflow.com/questions/4616202/self-references-in-object-literals-initializers) – e.g. one option is to use a getter. – Fabien Snauwaert Jun 03 '22 at 06:28

2 Answers2

8

You can declare your properties as functions

var obj = {
  prop1:1,
  prop2:function(){
    return this.prop1 + 1;
  }
}
Chop
  • 509
  • 2
  • 7
  • And is this the only way to accomplish this? I feel like using functions will make my code more complicated – JimiiBee Dec 13 '14 at 21:38
  • That would be the simplest way to accomplish this. Every time you call obj.prop2() you get a value relative to the current one of obj.prop1 – Chop Dec 13 '14 at 21:48
0

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.

Witiko
  • 3,167
  • 3
  • 25
  • 43