1

I have this object:

const obj = {
  thing: 5,
  layer: {
    otherThing: obj.thing - 2
  }
}

error:

ReferenceError: Cannot access 'obj' before initialization

I tried to use this but it didn't work as expected.

Pleklo
  • 126
  • 1
  • 2
  • 10

1 Answers1

1

This is not something you can do in JavaScript. But you have two possible alternatives here:

1)

    const obj = {thing: 5, layer: {}};
    obj.layer.otherThing = obj.thing - 2;

2) getters

    const obj = {
       thing: 5,
       layer: {
          get otherThing(){obj.thing - 2}
       }
    }
Max
  • 1,054
  • 1
  • 12
  • 20
Aditya Shankar
  • 702
  • 6
  • 12