Skip to content

JavaScript 类

ES6 类语法 for constructors, 方法, 继承, 静态成员, and 私有字段.

你将学到

  • Declaring 类使用 constructors and 方法
  • 继承使用 extends and super
  • 静态方法 and 属性 on 类它自己
  • 私有字段使用 # prefix (ES2022)
  • Getters and setters 使用获取 and 设置

概念讲解

Class Syntax

ES6 类 syntax is a cleaner way to write constructor functions and prototype methods. A 类 declaration creates a function (the constructor) with methods attached to its 原型. Under the hood, the prototype system is unchanged — classes are syntactic sugar that makes the code more readable and familiar to developers from other languages.

Constructor and Methods

The constructor is a special method that runs when you create an instance with 新. It initializes the instance's own properties. Other methods defined in the class body are placed on the prototype and shared by all instances. You can also define methods outside the constructor for behavior.

Inheritance with extends and super

类 Child extends Parent sets up the prototype chain so the child inherits the parent's methods. The child's constructor must call super(...) before using 这个. super.方法() calls the parent's version of a method, enabling override-and-extend patterns. This mirrors classical inheritance while remaining prototypal underneath.

Static Members

静态 methods and properties belong to the class itself, not to instances. They are called on the class (ClassName.方法()), useful for utility functions and factory methods. Static methods cannot access 这个 of an instance — they receive the class as 这个 when called on the class.

Private Fields and Accessors

ES2022 introduced truly private fields with the # prefix. A #balance field cannot be read or written from outside the class, giving real encapsulation without closures. The 获取 and 设置 keywords define accessor properties that run a function when a property is read or assigned — useful for validation and computed properties.

示例代码

              class Animal {
  #name; // private field — inaccessible outside the class

  constructor(name) {
    this.#name = name;
  }

  get name() {
    return this.#name;
  }

  speak() {
    return `${this.#name} makes a sound`;
  }

  static create(name) {
    return new Animal(name);
  }
}

class Dog extends Animal {
  #breed;

  constructor(name, breed) {
    super(name); // must call super before using 'this'
    this.#breed = breed;
  }

  speak() {
    return `${this.name} barks`; // override and extend
  }

  get info() {
    return `${this.name} (${this.#breed})`;
  }
}

const rex = new Dog("Rex", "Labrador");
console.log(rex.speak()); // "Rex barks"
console.log(rex.info);   // "Rex (Labrador)" — getter
// console.log(rex.#name); // SyntaxError — private

// Static method called on the class, not an instance
const generic = Animal.create("Creature");
console.log(generic.speak()); // "Creature makes a sound"

// instanceof checks the inheritance chain
console.log(rex instanceof Dog);   // true
console.log(rex instanceof Animal); // true
            

Shows 基础类 使用私有字段 and getter, subclass using extends and super, 方法 overriding, 静态 factory 方法, getter accessor, and instanceof 检查跨越链.

动手试一试

常见错误

错误写法

Forgetting 到 call super() in subclass constructor 之前 using 这个

正确做法

In subclass, 你必须 call super(...) 之前 accessing 这个. JavaScript throws ReferenceError 否则. Call super 首先, 然后设置实例属性.

错误写法

Trying 到 access 私有 (#) 字段从 之外类

正确做法

私有字段是 truly 私有 — 它们 cannot 是读取 or 编写之外类 请求体, 偶数通过 subclasses. Expose 它们通过 getter or 公共方法如果外部 access 是需要.

相关速查表

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误