JS Class

by kulimusoda

JavaScript

// 類別結構(定義屬性、方法)
class Animal {
  constructor(type, sound) {
    this.type = type
    this.sound = sound
  }

  makeSound() {
    console.log(`This is a ${this.type} and it goes ${this.sound}.`)
  }
}

// 繼承
class Bird extends Animal {
  constructor(type, sound, canfly) {
    super(type, sound)
    this.canfly = canfly
  }

  showFlyingAbility() {
    console.log(this.canfly ? "This bird can fly." : "This bird cannot fly.")
  }
}

// 靜態
class Zoo {
  static animalCount = 0
  static animals = []

  static addAnimal(name) {
    this.animalCount++
    this.animals.push(name)
  }

  static getAnimalCount() {
    console.log(`Total animals: ${this.animalCount}`)
  }

  static listAnimals() {
    console.log(`Animals in the zoo: ${this.animals.join(", ")}`)
  }
}

// 要求:
// 1. 創建一個 BankAccount 類別
// 2. 使用私有屬性 #balance
// 3. 添加 deposit() 和 withdraw() 方法
// 4. 添加邏輯:
//    - 存款金額必須大於0
//    - 提款金額不能超過餘額
//    - 不允許餘額小於0
// 5. 添加 getBalance() 方法顯示餘額

// 你的程式碼實作:
class BankAccount {
  #balance = 0

  constructor(initialBalance = 0) {
    if (initialBalance < 0) {
      throw new Error("初始金額必須大於0")
    }
    this.#balance = initialBalance
  }

  deposit(amount) {
    if (amount <= 0) {
      throw new Error("數目必須為正數")
    }
    this.#balance += amount
    return this.#balance
  }

  withdraw(amount) {
    if (amount <= 0) {
      throw new Error("數目必須為正數")
    }
    if (amount > this.#balance) {
      throw new Error("餘額不足")
    }
    this.#balance -= amount
    return this.#balance
  }
  
  getBalance(){
  return this.#balance
  }
}