Krok 2: klasa Student

Klasy i obiekty - JavaScript od podstaw: konsola (JavaScript)

Język ma na to osobną konstrukcję: klasę. `constructor` wywołuje się przy tworzeniu obiektu (`new Student(...)`) i ustawia pola przez `this`. Metody zapisane w klasie są wspólne dla wszystkich jej obiektów (nie kopiują się). Obiekt utworzony z klasy to jej instancja: `instanceof` to sprawdza. Wynik nadal ten sam.

class Student {
  constructor(name, grades) {
    this.name = name;
    this.grades = grades;
  }

  average() {
    return (this.grades.reduce((a, b) => a + b, 0) / this.grades.length).toFixed(2);
  }
}

const students = [
  new Student('Ola', [5, 4, 6]),
  new Student('Jan', [3, 4, 4, 5]),
  new Student('Ewa', [6, 5]),
];

for (const s of students) {
  console.log(`${s.name}: ${s.average()}`);
}
console.log(students[0] instanceof Student, typeof Student);

Ładowanie interaktywnego edytora... Jeśli się nie pojawi, włącz JavaScript.

Wszystkie lekcje kursu JavaScript od podstaw: konsola·Zaloguj się, aby zapisać postęp na koncie.