我想弄清楚为什么我不能调用我在课堂上设置的方法。我有一个es6课程
class school {
constructor(size = '10', subjects = {
math: 'green',
physics: 'green',
language: 'orange',
history: null
}) {
this.size = size;
this.subjects = subjects;
this.classCode = null;
}
changeSubject(study) {
this.classCode = this.subjects[study];
if (study === 'math') {
this.size += 1;
}
}
}
class room extends school {
constructor(roomQty = 15, size, subjects) {
super(size, subjects);
this.roomQty = roomQty;
}
changeStudy(study) {
super.changeStudy(study);
if (study === 'math') {
this.roomQty += 1;
}
}
gatherStudents() {
this.roomQty -= 3;
}
}
const myRoom = new room(10, 4);
当我使用console.log记录时,我收到一条未定义的消息。
console.log(myRoom.changeStudy('language'));
console.log(myRoom.gatherStudents());
console.log(myRoom.changeStudy('math'));
如何调用这些功能并将结果打印到控制台。
答案 0 :(得分:0)
您的代码存在一些问题。主要问题是你的方法没有返回任何东西,你的“超级”类没有实现引用的方法:
class school {
constructor(size = '10', subjects = {math: 'green', physics: 'green', language: 'orange', history: null}) {
this.size = size;
this.subjects = subjects;
this.classCode = null;
this.study = null
}
changeStudy(study) {
this.study = study
}
changeSubject(study) {
this.classCode = this.subjects[study];
if (super.study === 'math') {
this.size += 1;
}
}
}
class room extends school {
constructor(roomQty = 15, size, subjects) {
super(size, subjects);
this.roomQty = roomQty;
}
changeStudy(study) {
super.changeStudy(study);
if (this.study === 'math') {
return this.roomQty += 1;
} else {
return 0
}
}
gatherStudents() {
return this.roomQty;
}
}
const myRoom = new room(10,4);
console.log(myRoom.changeStudy('language'));
console.log(myRoom.gatherStudents());
console.log(myRoom.changeStudy('math'));