JavaScript: Класи та ООП

class та constructor

📖 Теорія

ES6 class — синтаксичний цукор над прототипами JS.

💡 Приклад коду
Вивід:

                            
📝 ЗАВДАННЯ (3)
1.
Завдання 1: Клас Person
10 XP
Створи клас Person з:
- constructor(name, birthYear)
- метод getAge() що повертає вік (2024 - birthYear)
- метод greet() що повертає 'Привіт, мене звати [name], мені [age] років'

Виведи greet() для Person('Оля', 1998) та Person('Максим', 2001).
💡 Підказка: this.name та this.birthYear в constructor. Виклич this.getAge() всередині greet()
🔓 Розв'язок:
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());
Вивід:

                                

2.
Завдання 2: Статичний метод та фабрика
20 XP
Розшир клас Person:
- статичний метод fromString(str) де str = 'Ім\'я:рік' (напр. 'Іван:1990')
- гетер fullDescription що повертає '[name] (народився у [birthYear])'

Виведи Person.fromString('Соломія:1995').fullDescription
💡 Підказка: static fromString(str) { const [name, year] = str.split(':'); return new Person(name, Number(year)); }
🔓 Розв'язок:
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);
Вивід:

                                

3.
Завдання 3: Клас BankAccount
30 XP
Реалізуй клас BankAccount:
- constructor(owner, initialBalance = 0)
- deposit(amount) — поповнення, повертає новий баланс
- withdraw(amount) — зняття (якщо недостатньо коштів — виведи 'Недостатньо коштів')
- гетер balance

Виведи операції для рахунку з 1000 грн: поповни 500, зніми 300, зніми 1500, фінальний баланс.
💡 Підказка: Зберігай баланс у приватному полі #balance або звичайному _balance
🔓 Розв'язок:
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);
Вивід: