У меня есть два класса, класс environment
имеет свойство станций, которые должны иметь несколько экземпляров класса 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;
}
}
Вы можете попробовать это, добавив ссылку на среду на такие станции, как:
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;
}
}
О, я вижу, атрибут «имя» в среде уникален? Может быть, вы могли бы хранить только имя внутри станции вместо ссылки, а затем искать по имени нужное окружение?
Затем, когда я пытаюсь преобразовать его в JSON и отправить с помощью res.send() (в Express), я получаю «TypeError: Преобразование циклической структуры в JSON», есть идеи, что делать?