ReferenceError: Cannot access 'obj' before initialization

ReferenceError: Cannot access 'obj' before initialization

我有这个对象:

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

错误:

ReferenceError: Cannot access 'obj' before initialization

我尝试使用 this 但它没有按预期工作。

这不是您在 JavaScript 中可以做的事情。但是这里有两种可能的选择:

1)

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

2) 吸气剂

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