Heute lernst du:
#)this-NuancenAm Ende kannst du robuste Klassen mit Kapselung und Methoden erstellen.
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
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
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
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());
Erstelle eine BankAccount-Klasse:
#balancedeposit(amount) und withdraw(amount)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