三行代码  ›  专栏  ›  技术社区  ›  Iftach

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

  •  0
  • Iftach  · 技术社区  · 3 月前

    我有两门课,第一门 environment 类有一个stations属性,该属性应该有 station 班我试图在站点中添加一个增加方法,该方法将增加站点的值,并将父环境的挂起值减少相同的量。我一直想和你乱搞 super , parent Object.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;
      }
    }
    
    1 回复  |  直到 3 月前
        1
  •  1
  •   Veso Alex    3 月前

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

    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;
      }
    }