繁体   English   中英

es6日志记录功能未定义

[英]es6 logging function are undefined

我试图弄清楚为什么我不能调用在类中设置的方法。 我在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'));

我如何调用这些函数并将结果打印到控制台。

您的代码有几个问题。 主要问题是您的方法不返回任何内容,并且您的“ super”类未实现所引用的方法:

 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')); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM