类(Class)

ES6 引入的类语法,提供更清晰的面向对象编程方式。


📚 基本语法

类声明

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  
  greet() {
    return `Hello, I'm ${this.name}`;
  }
}
 
const person = new Person('Alice', 30);
console.log(person.greet()); // "Hello, I'm Alice"

类表达式

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

🎯 类特性

1. 构造函数(Constructor)

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

2. 方法定义

class Calculator {
  add(a, b) {
    return a + b;
  }
  
  subtract(a, b) {
    return a - b;
  }
}

3. 静态方法(Static Methods)

class MathUtils {
  static add(a, b) {
    return a + b;
  }
  
  static PI = 3.14159;
}
 
// 通过类调用,不需要实例
console.log(MathUtils.add(1, 2)); // 3
console.log(MathUtils.PI); // 3.14159

4. 私有字段(Private Fields)

class BankAccount {
  #balance = 0; // 私有字段
  
  deposit(amount) {
    this.#balance += amount;
  }
  
  getBalance() {
    return this.#balance;
  }
}
 
const account = new BankAccount();
account.deposit(100);
console.log(account.getBalance()); // 100
// console.log(account.#balance); // ❌ 错误:私有字段无法访问

5. 私有方法(Private Methods)

class BankAccount {
  #balance = 0;
  
  #validateAmount(amount) { // 私有方法
    return amount > 0;
  }
  
  deposit(amount) {
    if (this.#validateAmount(amount)) {
      this.#balance += amount;
    }
  }
}

🔄 继承(Inheritance)

extends 关键字

class Animal {
  constructor(name) {
    this.name = name;
  }
  
  speak() {
    return `${this.name} makes a sound`;
  }
}
 
class Dog extends Animal {
  constructor(name, breed) {
    super(name); // 调用父类构造函数
    this.breed = breed;
  }
  
  speak() {
    return `${this.name} barks`;
  }
}
 
const dog = new Dog('Buddy', 'Golden Retriever');
console.log(dog.speak()); // "Buddy barks"

super 关键字

class Animal {
  constructor(name) {
    this.name = name;
  }
  
  move() {
    return `${this.name} moves`;
  }
}
 
class Bird extends Animal {
  move() {
    return super.move() + ' by flying'; // 调用父类方法
  }
}

🎨 高级特性

1. Getter 和 Setter

class Person {
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }
  
  get fullName() {
    return `${this.firstName} ${this.lastName}`;
  }
  
  set fullName(name) {
    [this.firstName, this.lastName] = name.split(' ');
  }
}
 
const person = new Person('John', 'Doe');
console.log(person.fullName); // "John Doe"
person.fullName = 'Jane Smith';
console.log(person.firstName); // "Jane"

2. 计算属性名

const methodName = 'calculate';
 
class Calculator {
  [methodName](a, b) {
    return a + b;
  }
}
 
const calc = new Calculator();
console.log(calc.calculate(1, 2)); // 3

3. 类字段(Class Fields)

class Counter {
  count = 0; // 类字段(实例属性)
  static total = 0; // 静态类字段
  
  increment() {
    this.count++;
    Counter.total++;
  }
}

⚠️ 注意事项

1. 类不会提升

// ❌ 错误:类不会提升
const person = new Person(); // ReferenceError
class Person {}

2. 类体在严格模式下运行

class MyClass {
  // 自动启用严格模式
  method() {
    x = 10; // ❌ 错误:x is not defined
  }
}

3. 类方法不可枚举

class Person {
  greet() {}
}
 
const person = new Person();
console.log(Object.keys(person)); // [](方法不可枚举)

4. 必须使用 new 调用

class Person {}
 
// ❌ 错误:必须使用 new
const person = Person(); // TypeError
 
// ✅ 正确
const person = new Person();

🔄 与构造函数对比

构造函数方式

function Person(name) {
  this.name = name;
}
 
Person.prototype.greet = function() {
  return `Hello, I'm ${this.name}`;
};

类方式

class Person {
  constructor(name) {
    this.name = name;
  }
  
  greet() {
    return `Hello, I'm ${this.name}`;
  }
}

类语法本质上是构造函数的语法糖,但提供了:

  • 更清晰的语法
  • 更好的错误检查
  • 更直观的继承语法

💡 最佳实践

1. 使用类字段初始化

class User {
  name = '';
  email = '';
  isActive = false;
  
  constructor(name, email) {
    this.name = name;
    this.email = email;
  }
}

2. 使用私有字段保护数据

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

3. 使用静态方法处理工具函数

class MathUtils {
  static add(a, b) {
    return a + b;
  }
  
  static multiply(a, b) {
    return a * b;
  }
}

🔗 相关链接


参考


javascript class 面向对象 oop