ES6 class — синтаксичний цукор над прототипами JS.
class Person {
constructor(name, birthYear) {
this.name = name;
this.birthYear = birthYear;
}
getAge() { return 2024 - this.birthYear; }
greet() { return `Привіт, мене звати ${this.name}, мені ${this.getAge()} років`; }
}
console.log(new Person('Оля', 1998).greet());
console.log(new Person('Максим', 2001).greet());
class Person {
constructor(name, birthYear) {
this.name = name;
this.birthYear = birthYear;
}
getAge() { return 2024 - this.birthYear; }
get fullDescription() { return `${this.name} (народився у ${this.birthYear})`; }
static fromString(str) {
const [name, year] = str.split(':');
return new Person(name, Number(year));
}
}
console.log(Person.fromString('Соломія:1995').fullDescription);
class BankAccount {
#balance;
constructor(owner, initialBalance = 0) {
this.owner = owner;
this.#balance = initialBalance;
}
deposit(amount) { this.#balance += amount; return this.#balance; }
withdraw(amount) {
if (amount > this.#balance) { console.log('Недостатньо коштів'); return this.#balance; }
this.#balance -= amount; return this.#balance;
}
get balance() { return this.#balance; }
}
const acc = new BankAccount('Андрій', 1000);
console.log(acc.deposit(500));
console.log(acc.withdraw(300));
acc.withdraw(1500);
console.log(acc.balance);