Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Access and change properties of parent object in JS

I have two classes, the environment class has a property of stations which supposed to have multiple instances of the station class. I’m trying to add an increase method in the station that will increase the value of the station and will decrease the pending value of the parent environment by the same amount. I’ve tried to mess around with super, parent and Object.getPrototypeOf, but as I’m new to JavaScript OOP (and to JavaScript by itself) I’m struggling. Any help!

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You could try it by adding a reference for the environment to the stations like:

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;
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading