1

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);
Aleksandr
  • 439
  • 3
  • 13

4 Answers4

4

sum itself is suppose to be a JavaScript function. So this is valid:

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

    b: {
        value: 2
    },

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

You can learn more about object methods here.

Ultron
  • 21
  • 4
amanuel2
  • 4,508
  • 4
  • 36
  • 67
3

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...

dandavis
  • 16,370
  • 5
  • 40
  • 36
  • Thanks guys. Thanks. – Aleksandr Jan 10 '16 at 22:36
  • The **`get`** command acts as a shorthand for **[Object.defineProperty()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty)**. e.g. `Object.defineProperty(obj, "sum", { get: function() { return this.a.value + this.b.value; } });` – jherax Jan 10 '16 at 22:43
1

Inside the object initializer, the object has not been assigned to the variable obj yet. Then, obj is undefined, so you can't use obj.a.value.

But you can achieve something similar by instantiating an anonymous function:

var obj = new function() {
  this.a = {
    value: 1
  };
  this.b = {
    value: 2
  };
  this.sum = {
    value: this.a.value + this.b.value
  };
};
Oriol
  • 274,082
  • 63
  • 437
  • 513
  • 1
    this is a good example of an anon constructor. i think with `Object.assign` to cleanup the statics/reduce weight, this should be more popular of a pattern than we see out there. it's a good suggestion. of course there's a balance and this costs more than a literal, but i like the ability to init with arbitrary code... – dandavis Jan 10 '16 at 22:49
0

It looks like you trying to add a method to your Object, if so it should be like so:

var obj = {
  a: {
    value: 1
  },
  b: {
    value: 2
  },
  sum:function() {
    return this.a.value + this.b.value
  }
};

console.log(obj.sum); //Returns the function object
console.log(obj.sum()); //Returns the value 3
sjm
  • 5,378
  • 1
  • 26
  • 37