StudyCode
Синтаксис class, конструктор, методы, геттеры/сеттеры, static и приватные поля.
class Animal {
constructor(name, sound) {
this.name = name; // публичное поле
this.sound = sound;
this.#energy = 100; // приватное поле (ES2022)
}
speak() { // метод
return `${this.name}: ${this.sound}!`;
}
static create(name, sound) { // статический метод
return new Animal(name, sound);
}
get info() { // геттер
return `${this.name} (энергия: ${this.#energy})`;
}
set energy(val) { // сеттер
if (val < 0) throw new Error("Энергия не может быть отрицательной");
this.#energy = val;
}
#energy; // объявление приватного поля
}
const cat = new Animal("Мурка", "Мяу");
cat.speak(); // "Мурка: Мяу!"
cat.info; // "Мурка (энергия: 100)"
cat.energy = 80; // сеттер
Animal.create("Рекс", "Гав"); // статический методclass BankAccount {
#balance;
#transactions = [];
constructor(owner, initialBalance = 0) {
this.owner = owner;
this.#balance = initialBalance;
}
deposit(amount) {
if (amount <= 0) throw new Error("Сумма должна быть положительной");
this.#balance += amount;
this.#transactions.push({ type: "deposit", amount });
return this; // для цепочки вызовов
}
withdraw(amount) {
if (amount > this.#balance) throw new Error("Недостаточно средств");
this.#balance -= amount;
this.#transactions.push({ type: "withdraw", amount });
return this;
}
get balance() { return this.#balance; }
get history() { return [...this.#transactions]; }
toString() {
return `${this.owner}: ${this.#balance} руб.`;
}
}
const acc = new BankAccount("Аня", 1000);
acc.deposit(500).withdraw(200); // цепочка
console.log(acc.balance); // 1300Что такое геттер в классе?
Каждый объект имеет скрытую ссылку [[Prototype]] на другой объект. Нажми на узел цепочки, чтобы увидеть его свойства.