简体   繁体   中英

es6 logging function are undefined

I am trying to figure out why i cannot call methods i have set in my classes. I have a class in 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);

When I log this using console.log, I get an undefined message.

console.log(myRoom.changeStudy('language'));
console.log(myRoom.gatherStudents());
console.log(myRoom.changeStudy('math'));

How can i call these function and print the results to the console.

There were several problems with your code. The main problem was that your methods do not return anything and that your "super" Class did not implement the referenced method:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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