Код выдает ошибку Uncaught TypeError: Cannot read properties of undefined

Рейтинг: 0Ответов: 1Опубликовано: 28.01.2023

Проблема код выдает ошибку

mainScripts.js:84 Uncaught TypeError: Cannot read properties of undefined (reading 'length') at Calculation.amountOfClasses (mainScripts.js:84:36) at mainScripts.js:109:11

Не понимаю как данную ошибку устранить.

Мой код:

class Student {
    constructor(firstName,lastName,yearOfBirth,arrayOfGrades) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.yearOfBirth = yearOfBirth;
        this.arrayOfGrades = arrayOfGrades;
    }
    //______Возраст студента______//
    getAge (yearOfBirth) {
        return console.log(`${this.firstName}'s old is ${2023 - yearOfBirth} years`);
    }
    //______Средний бал______//
    averageMark (arrayOfGrades) {
        let sum = 0;
        for (let i = 0; i < arrayOfGrades.length; i++) {
            sum = sum + arrayOfGrades[i];
        }
        return console.log(`${this.firstName}'s average mark is ${sum / arrayOfGrades.length}`);
    }

}
// //______Экземпляры студентов______//
const student = new Student('Dmitriy','Yaroshchuk',2001,[70,80,90,100,90,90,99,100,95,100]);
const student1 = new Student('Andrew','Kavetsky',2000,[90,90,90,90,90,90,100,100,95,93]);
const student2 = new Student('Diana','Koko',1999,[70,70,70,70,70,70,75,75,75,93]);

//______Передаю значения в методы______//
student.getAge(2001);
student1.getAge(2000);
student2.getAge(1999);
student.averageMark([70,80,90,100,90,90,99,100,95,100]);
student1.averageMark([90,90,90,90,90,90,100,100,95,93]);
student2.averageMark([70,70,70,70,70,70,75,75,75,93]);

class Visit extends Student {
    constructor() {
        super();
        this.visitinMagazine = [];
    }
    //______Используется когда студент был на занятие______//
    present () {
        if (this.visitinMagazine.length < 26) {
            this.visitinMagazine.push(true);
            return this;
        } else {
            return this.visitinMagazine.pop();
        }
    }
    //______Используется когда студент НЕ был на занятие______//
    absent () {
        if (this.visitinMagazine.length < 26) {
            this.visitinMagazine.push(false);
            return this;
        } else {
            return this.visitinMagazine.pop();
        }
    }
}
// //______Экземпляры посейщения______//
const visit = new Visit();
const visit1 = new Visit();
const visit2 = new Visit();

//______Посейщение уроков______//
visit.present().present().present().present().present().present().present().present().present().present().present().present().present().present().present().present().present().present().present().present().present().present().present().absent().absent();
console.log(visit.visitinMagazine);

//______Посейщение уроков______//
visit1.absent().absent().absent().absent().absent().absent().absent().absent().absent().absent().absent().absent().absent().absent().absent().absent().absent().absent().absent().absent().absent().absent().absent().present().present();
console.log(visit1.visitinMagazine);

//______Посейщение уроков______//
visit2.present().present().present().present().present().present().present().present().present().present().present().present().present().present().present().present().present().present().present().present().present().present().absent().absent().absent();
console.log(visit2.visitinMagazine);


 class Calculation extends Visit {
    constructor() {
        super();
    }
     //______Колличество занятий______//
     amountOfClasses () {
         return this.arrayOfGrades.length;
     }
     //______Колличество посищений______//
     amountOfVisits () {
         return this.visitinMagazine.filter((element) => element === true).length;
     }
     //______Проверяем среднюю оценку и посейщение______//
     summary () {
         const averageVisit = this.amountOfVisits / this.amountOfClasses;
         if (this.averageMark > 90 && averageVisit > 0.9) {
             return console.log('Cool!');
         } else if (this.averageMark > 90 || averageVisit > 0.9) {
             return console.log('Good, but it can be better!');
         } else {
             return console.log('Radish');
         }
     }
 }
// //______Экземпляры расчетов______//
const calculate = new Calculation();
const calculate1 = new Calculation();
const calculate2 = new Calculation();
calculate.summary();
calculate1.summary();
calculate2.summary();
calculate.amountOfClasses();
calculate.amountOfVisits();

Ответы

▲ 1Принят

Покажу на минимальном примере, как работать с классами и передавать данные в конструкторы наследуемых классов:

Что бы передать данные в конструктор родительского класса используется ключевое слово super(), в котором необходимо передать данные.
super(...) вызывает constructor() родителя. Использование super возможно только внутри constructor() текущего класса.

class First {
  constructor(one, two) {
    this.one = one;
    this.two = two;
    this.def = [];
  }

  oneShow() {
    console.log(this)
  }
}

class Second extends First {
  constructor(one, three) {
    super(one);
    this.three = three;
  }

  twoShow() {
    console.log(this);
  }
}

class Threed extends Second{
  constructor() {
    super();
  }

  threeShow() {
    console.log(this);
  }
}

const one = new First(1, 2);
one.oneShow();
const two = new Second(3, 4);
two.twoShow();
const two_null = new Second();
two_null.twoShow();
const three = new Threed();
three.threeShow();
const three_param = new Threed(6, 7, 8);
three_param.threeShow();

Обратите внимание, что в классе Second в super передается только одно значение, как следствие this.two остается undefined.
Так же this.def имеет свойство по умолчанию, поэтому во всех экземплярах класса оно имеет начальное значение.

При создании two_null не передаются какие либо значения, как следствие, все значения, кроме this.def являются undefined

В классе Threed в super не передается никакое значение, поэтому все данные будут undefined, кроме this.def