34. class 是语法糖吗?背后发生了什么? 副本.md

查看飞书原文 ↗2,552 字符

1. 核心概念 (Core Concept)

class 是 JavaScript ES6 (ECMAScript 2015) 引入的一种新的语法,用于定义类。它旨在提供一种更清晰、更简洁的方式来创建对象及其继承。

2. 为什么需要它? (The "Why")

尽管在 ES6 之前,JavaScript 已经可以通过原型链(Prototype Chain)实现面向对象的编程,但存在以下问题:

class 语法糖的引入,极大地提升了代码的可读性和可维护性,使其更接近于传统面向对象语言(如 Java, C++)的类定义方式。

3. API 与用法 (API & Usage)

class 的核心用法包括类的定义、构造函数、方法、静态方法、继承等。

3.1 类定义与构造函数

class MyClass {
  // 构造函数,在使用 new 关键字创建实例时调用
  constructor(value) {
    this.property = value; // 实例属性
  }

  // 实例方法
  myMethod() {
    console.log(this.property);
  }

  // 静态方法,通过类本身调用,而不是实例
  static staticMethod() {
    console.log('This is a static method.');
  }
}

// 创建类的实例
const instance = new MyClass('hello');
instance.myMethod(); // 输出: hello
MyClass.staticMethod(); // 输出: This is a static method.
// instance.staticMethod(); // 错误!静态方法不能通过实例调用

3.2 继承

使用 extends 关键字实现类的继承:

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

  greet() {
    console.log(`Hello, ${this.name}`);
  }
}

class DerivedClass extends BaseClass {
  constructor(name, age) {
    // 调用父类的构造函数
    super(name);
    this.age = age;
  }

  // 重写父类方法
  greet() {
    // 调用父类的 greet 方法
    super.greet();
    console.log(`I am ${this.age} years old.`);
  }
}

const derivedInstance = new DerivedClass('Alice', 30);
derivedInstance.greet();
// 输出:
// Hello, Alice
// I am 30 years old.

4. 关键注意事项 (Key Considerations)

5. 参考资料 (References)



原文链接与附件索引