Aleksandr Aleksandr - 2 months ago 19
Javascript Question

Get object property value

This will not help. How get

obj
of the property sum?

var obj = {
a: {
value: 1
},

b: {
value: 2
},

sum: {
value: obj.a.value + obj.b.value
}
};

console.log(obj.sum);

Answer

you need to use in inline getter to code self-reflecting expressions in literals like that:

var obj = {
  a: {
    value: 1
  },

  b: {
    value: 2
  },

  get sum(){
    return this.a.value + this.b.value
  }
};

console.log(obj.sum); // shows: 3

this is ES5, but often over-looked. it works in all major browsers (even IE8) and node.

the getter syntax is nice because obj.sum both acts like a number and stays updated automatically as a and b change.

of course, it's probably more traditional to use a method (a function) and call it like obj.sum(), as that indicates to other coders that it's a "computed property" more or less...