ES6-class

113 阅读2分钟

1. 定义与构造方法

  • 使用 class 关键字定义类
  • constructor 方法是类的构造函数,用于初始化实例属性
  • greet 是一个实例方法,this 关键字指向类的实例。
  • 示例:
class Animal {
  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.`);
  }
}

2、创建实例

通过new关键字创建类的实例

const person1 = new Person('Alice', 30);
person1.greet(); // 输出: Hello, my name is Alice and I am 30 years old.

3、继承与多态

使用 extends 实现继承,super 调用父类方法;子类可重写父类方法实现多态。

class Employee extends Person {
  constructor(name, age, jobTitle) {
    super(name, age); // 调用父类的 constructor
    this.jobTitle = jobTitle;
  }

  introduce() {
    console.log(`I am a(n) ${this.jobTitle} and my name is ${this.name}.`);
  }
}

const emp = new Employee('Bob', 28, 'Engineer');
emp.greet(); // 输出: Hello, my name is Bob and I am 28 years old.
emp.introduce(); // 输出: I am a(n) Engineer and my name is Bob.

4、静态方法(static)

静态方法属于类本身,而不是类的实例,不能通过实例调用,只能通过类名来调用。

class MathHelper {
  static add(a, b) {
    return a + b;
  }
}

console.log(MathHelper.add(2, 3)); // 输出: 5

5. Getter 和 Setter

ES6 还支持在类中定义 getter 和 setter 来访问和修改属性。

class Rectangle {
  constructor(width, height) {
    this.width = width;
    this.height = height;
  }

  get area() {
    return this.width * this.height;
  }

  set width(value) {
    if (value <= 0) {
      console.log('Width must be positive');
    } else {
      this._width = value;
    }
  }

  get width() {
    return this._width;
  }
}

const rect = new Rectangle(10, 20);
console.log(rect.area); // 输出: 200
rect.width = -5; // 输出: Width must be positive

6. Private 和 # 前缀

ES2022(即 ECMAScript 2022)引入了私有字段和方法,使用 # 前缀来定义。私有成员只能在类的内部访问,外部无法直接访问。

class BankAccount {
  #balance = 0;

  deposit(amount) {
    if (amount > 0) {
      this.#balance += amount;
    }
  }

  getBalance() {
    return this.#balance;
  }
}

const account = new BankAccount();
account.deposit(100);
console.log(account.getBalance()); // 输出: 100
console.log(account.#balance); // 会抛出错误,因为 #balance 是私有的

注意:private是ts里的内容,而非 js 中的关键字!

7、与函数构造器的区别

  • class 语法更清晰,支持显式继承和封装,替代 ES5 的原型链模式。