How do I reference the same Object's properties during its creation? [duplicate]

I'm trying to do someting like

o = {
  a: { foo: 42 },
  b: o.a
}

But that returns an error saying o is not defined. I know I can later do o.b = o.a. But I'm wondering if it's possible to define b while I'm in defining o.


This is ancient history now, but I just learned about getters and setters, which are perfect for your situation, and I'm sure people looking at this issue could get some value from it..

o = {
  a: { foo: 42 },
  get b() {
    return this.a
    }
  }

console.log(o.b) // => { foo: 42 }

As @RobG commented — no, you can't.

You can, however, use the this keyword inside of functions defined as properties of the object, like so:

o = {
  a: { foo: 42 },
  b: function () {
      return this.a;
  }
}

console.log(o.b()); // {foo: 42};