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;
}
}
CodePudding user response:
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;
}
}