JavaScript Fortgeschritten Tag 2: Erweiterte Objekte & Klassen

Ziel des Tages

Heute lernst du:

Am Ende kannst du robuste Klassen mit Kapselung und Methoden erstellen.

Schritt 1: ES6 Klassen

Verwende das class-Keyword zur Definition von Objekten:


class Person {
  #age;
  constructor(name, age) {
    this.name = name;
    this.#age = age;
  }
  getAge() {
    return this.#age;
  }
}

const john = new Person("John", 30);
console.log(john.getAge()); // 30

Schritt 2: Getter & Setter

Zugriff auf private Felder kapseln:


class Person {
  #age;
  constructor(name, age) {
    this.name = name;
    this.#age = age;
  }

  get age() {
    return this.#age;
  }

  set age(value) {
    if(value >= 0) this.#age = value;
  }
}

const alice = new Person("Alice", 25);
console.log(alice.age); // 25
alice.age = 30;
console.log(alice.age); // 30

Schritt 3: Methoden & this-Nuancen

Methoden in Klassen verwenden this, um auf Eigenschaften zuzugreifen:


class Person {
  constructor(name) {
    this.name = name;
  }
  greet() {
    console.log(`Hallo, ich bin ${this.name}`);
  }
}

const bob = new Person("Bob");
bob.greet(); // Hallo, ich bin Bob

Übung


class Person {
  #age;
  constructor(name, age) {
    this.name = name;
    this.#age = age;
  }
  getAge() { return this.#age; }
}

const john = new Person("John", 30);
console.log(john.getAge());

Aufgabe

Erstelle eine BankAccount-Klasse:

Beispiel:


class BankAccount {
  #balance;
  
  constructor(initialBalance = 0) {
    this.#balance = initialBalance;
  }
  
  deposit(amount) {
    if(amount > 0) this.#balance += amount;
  }
  
  withdraw(amount) {
    if(amount <= this.#balance) this.#balance -= amount;
  }
  
  getBalance() {
    return this.#balance;
  }
}

const account = new BankAccount(100);
account.deposit(50);
account.withdraw(30);
console.log(account.getBalance()); // 120