类与对象

在JavaScript中,面向对象编程(OOP)是一种重要的编程范式。它允许开发者创建可重用、可维护的代码。面向对象编程的核心概念包括类(Class)和对象(Object)。

类

类是对象的蓝图或模板,它定义了对象的属性(属性和方法)和行为(方法)。在JavaScript中,可以使用ES6(ECMAScript 2015)语法来定义一个类。

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  greet() {
    console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
  }
}

在上面的例子中,Person 类有两个属性:name 和 age,以及一个方法 greet。

对象

对象是类的实例。当你创建一个类的实例时,你实际上创建了一个具有类定义的所有属性和方法的对象。

const person1 = new Person('Alice', 25);
const person2 = new Person('Bob', 30);

person1.greet(); // 输出: Hello, my name is Alice and I am 25 years old.
person2.greet(); // 输出: Hello, my name is Bob and I am 30 years old.

在上面的例子中,person1 和 person2 都是 Person 类的实例。

继承

继承是面向对象编程的另一个核心概念。它允许一个类继承另一个类的属性和方法。

基类与派生类

在JavaScript中,你可以使用 extends 关键字来创建一个派生类。

class Employee extends Person {
  constructor(name, age, id) {
    super(name, age);
    this.id = id;
  }

  showId() {
    console.log(`Employee ID: ${this.id}`);
  }
}

在上面的例子中,Employee 类继承自 Person 类。Employee 类有一个额外的属性 id 和一个方法 showId。

使用继承

使用继承创建实例:

const employee1 = new Employee('Alice', 25, 'E12345');
employee1.greet(); // 输出: Hello, my name is Alice and I am 25 years old.
employee1.showId(); // 输出: Employee ID: E12345

封装

封装是将对象的属性和方法包装在一起,以防止外部直接访问对象的状态。

属性访问器

属性访问器允许你使用getter和setter方法来控制属性的访问。

class Person {
  constructor(name, age) {
    this._name = name;
    this._age = age;
  }

  get name() {
    return this._name;
  }

  set name(newName) {
    this._name = newName;
  }

  get age() {
    return this._age;
  }

  set age(newAge) {
    if (newAge > 0) {
      this._age = newAge;
    }
  }
}

在上面的例子中,name 和 age 是私有属性,外部无法直接访问它们。通过getter和setter方法,可以控制对它们的访问。

实例解析

为了更好地理解面向对象编程,下面是一些具体的实例:

实例1:创建一个Car类

class Car {
  constructor(make, model, year) {
    this.make = make;
    this.model = model;
    this.year = year;
  }

  drive() {
    console.log(`${this.make} ${this.model} is driving.`);
  }
}

const myCar = new Car('Toyota', 'Corolla', 2020);
myCar.drive(); // 输出: Toyota Corolla is driving.

实例2:创建一个BankAccount类

class BankAccount {
  constructor(balance) {
    this.balance = balance;
  }

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

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

  getBalance() {
    return this.balance;
  }
}

const savingsAccount = new BankAccount(1000);
savingsAccount.deposit(200);
console.log(savingsAccount.getBalance()); // 输出: 1200
savingsAccount.withdraw(500);
console.log(savingsAccount.getBalance()); // 输出: 700

通过这些实例,你可以看到面向对象编程在JavaScript中的应用,以及如何创建可重用、可维护的代码。