在 JS 中访问和更改父对象的属性

Access and change properties of parent object in JS

我有两个 class,environment class 有一个 属性 个站点,应该有多个 station class。我正在尝试在站点中添加一个增加方法,该方法将增加站点的值并将父环境的待定值减少相同的数量。我试图弄乱 superparentObject.getPrototypeOf,但由于我是 JavaScript OOP(以及 JavaScript 本身)的新手我正在挣扎。任何帮助!

class enviroment {
  constructor(name) {
    this.name = name;
    this.pending = 0;
    this.stations = [];
  }

  newStation(value = 0, name = null) {
    this.stations.push(new station(value, name));
    return this;
  }
}

class station {
  constructor(value = 0, label = null) {
    this.value = value;
    this.label = label;
    this.isTaken = false;
  }

  increase(increasment) {
    this.value += increasment;
    this.parent.pending -= increasment; // <---- HERE
    return this;
  }
}

您可以通过向站点添加环境参考来尝试它,例如:

class enviroment {
  constructor(name) {
    this.name = name;
    this.pending = 0;
    this.stations = [];
  }

  newStation(value = 0, name = null) {
    this.stations.push(new station(value, name, this));
    return this;
  }
}

class station {
  constructor(value = 0, label = null, environment = null) {
    this.value = value;
    this.label = label;
    this.isTaken = false;
    this.environment = environment;
  }

  increase(increasment) {
    this.value += increasment;
    if(this.environment)
      this.environment.pending -= increasment; // <---- HERE
    return this;
  }
}