ReferenceError:初始化之前无法访问'obj'[重复]

问题描述 投票:0回答:1

我有这个对象:

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

错误:

ReferenceError: Cannot access 'obj' before initialization

我尝试使用this,但未如预期那样工作。

javascript node.js object this
1个回答
1
投票

这是您无法使用javascript执行的操作,您在这里有2种可能的选择,

1

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

2。吸气剂

const obj = {
   thing: 5,
   layer: {
      get otherThing(){obj.thing - 2}
   }
}
© www.soinside.com 2019 - 2024. All rights reserved.