0

I have an object like:

var Magic = {
  value: undefined,
  setValue: function (value) {
    this.value = value
    return this.value
  },
  one: this.value
};

and after I ran the following code:

console.log(Magic.setValue(1)) // 1
console.log(Magic.value) // 1
console.log(Magic.one) // undefined

Look at here: Magic.value === 1 but Magic.one === undefined, since I assign one:this.value.

So why would this happen? Where did this on one:this.value point to? How can I assign one property with the value of property value?

Liam
  • 25,247
  • 27
  • 110
  • 174
Halt
  • 965
  • 8
  • 18
  • 1
    See http://stackoverflow.com/questions/3975859/what-are-the-differences-between-json-and-javascript-object for the difference between an object and JSON. – Joe Clay Jul 07 '16 at 09:21
  • `one` refers to whatever `this.value` was at the time of defining the object. It does not re-evaluate every time you access `one`. It's no different than `var foo = bar` or `var foo = { bar: baz }`. – deceze Jul 07 '16 at 09:23
  • [Object inline declaration self references](http://stackoverflow.com/questions/4616202/self-references-in-object-literal-declarations) – Veverke Jul 07 '16 at 09:25

0 Answers0