Как связать два класса между собой?
Ребята кто силен в JS, подскажите пожалуйста. Как получить данные о названии школы? Хотелось бы в классе Children получить ссылку на класс School для того что бы не дублировать данные из за наследования.
class Sсhool{
nameScool;
constructor(setNameScool){
this.nameScool=setNameScool;
}
addChildren(children){
this[children.nameChild] = children;
}
}
class Children{
constructor(setName, setAge){
this.nameChild = setName;
this.ageChild = setAge;
}
getInfo(){
console.log(`Учится в школе - ${this.nameScool}`)
}
}
const school = new Sсhool('Школа 1');
const alex = new Children("Alex", 12)
school.addChildren(alex)
alex.getInfo()
Ответы (1 шт):
Автор решения: Алексей Шиманский
→ Ссылка
class Sсhool{
nameScool;
constructor(setNameScool){
this.nameScool=setNameScool;
}
addChildren(children){
this[children.nameChild] = children;
}
getName() {
return this.nameScool;
}
}
class Children{
constructor(setName, setAge, school = null){
this.nameChild = setName;
this.ageChild = setAge;
this.school = school;
}
getInfo(){
let info = `Имя: ${this.nameChild}, возраст: ${this.ageChild}, `;
info += this.school ? `учится в школе «${this.school.getName()}»` : 'в школе не учится';
console.log(info);
}
}
const school = new Sсhool('Школа 1');
const alex = new Children("Alex", 12, school)
alex.getInfo()