面向对象编程(OOP)是 JavaScript 中一种重要的编程范式。它允许开发者将数据和行为封装在一起,创建出更加模块化和可重用的代码。

类和对象

在 JavaScript 中,我们可以使用 class 关键字来定义一个类,类是创建对象的蓝图。

class Animal {
  constructor(name) {
    this.name = name;
  }

  speak() {
    console.log(`${this.name} makes a sound.`);
  }
}

const dog = new Animal('Dog');
dog.speak(); // Dog makes a sound.

继承

JavaScript 支持继承,这意味着一个类可以继承另一个类的属性和方法。

class Dog extends Animal {
  constructor(name) {
    super(name);
  }

  bark() {
    console.log(`${this.name} barks.`);
  }
}

const myDog = new Dog('Buddy');
myDog.speak(); // Buddy makes a sound.
myDog.bark(); // Buddy barks.

封装

封装是 OOP 的核心原则之一,它允许我们隐藏实现细节,只暴露必要的接口。

class BankAccount {
  constructor(balance) {
    this._balance = balance; // 私有属性
  }

  getBalance() {
    return this._balance;
  }

  deposit(amount) {
    this._balance += amount;
  }

  withdraw(amount) {
    if (amount <= this._balance) {
      this._balance -= amount;
    }
  }
}

扩展阅读

想要了解更多关于 JavaScript 面向对象编程的知识,可以阅读以下链接:


```html
<center><img src="https://cloud-image.ullrai.com/q/JavaScript_Class_/" alt="JavaScript_Class"/></center>