类:用 class 描述一批对象,再看清它背后的原型
学习平台里有几十名学员,每人都有姓名和分数,都要能生成一句成绩说明。写两个对象字面量还能忍,写到第十个,你会发现同样的属性名和同一个方法被抄了十遍,哪天说明的格式要改,十个地方得一起改,漏一处就出 bug。
class 解决的就是这件事:把“这一类对象长什么样、能做什么”写在一处,再用 new 批量造出数据各不相同的实例(instance)。但要先说清一点:JavaScript 的类是建立在原型上的语法,没有换掉原型。类里的普通方法仍然存在 prototype 上,继承仍然靠原型链。把这层关系弄明白,constructor、static、extends、super 就不再是一堆要背的关键字。
文中的控制台示例在 Node.js v25.2.1 下运行过,输出照抄真实结果。个别报错信息的措辞是 V8 引擎的写法,换成其他引擎文字会不同,但错误类型一致。示例只用语言本身的能力,浏览器控制台里核心结果相同;章中嵌入的交互工具需要在浏览器页面里操作。
学习路线
完成本章后,你应该能够:
- 用
class定义模板,用new创建互相独立的实例; - 用
constructor、默认参数和公共字段初始化实例; - 判断一个成员在实例上、
prototype上,还是在类本身上; - 用 getter、setter 和私有字段给数据设一道关卡;
- 用
static写不依赖具体实例的能力; - 用
extends与super复用并改写父类行为; - 沿原型链解释方法查找、属性遮蔽和
instanceof; - 认出忘写
new、this丢失、滥用继承这几类常见问题。
从重复的对象到一份模板
对象字面量适合描述一个具体的东西。要是两个对象结构一样,就得把属性名和方法各写一遍:
const studentA = {
name: "小林",
score: 92,
intro() {
return `${this.name}:${this.score} 分`;
},
};
const studentB = {
name: "小周",
score: 88,
intro() {
return `${this.name}:${this.score} 分`;
},
};把共同的部分提出来,就是一个类。类名习惯用大驼峰,比如 Student、OrderItem:
class Student {
constructor(name, score = 0) {
this.name = name;
this.score = score;
}
intro() {
return `${this.name}:${this.score} 分`;
}
}
const a = new Student("小林", 92);
const b = new Student("小周", 88);
console.log(a.intro());
console.log(b.intro());
console.log(a === b, a instanceof Student);小林:92 分
小周:88 分
false truenew Student(...) 每执行一次就产生一个新对象,所以 a === b 是 false。两个实例的数据各存各的,改一个不会牵动另一个:
a.score = 95;
console.log(a.score, b.score);95 88那 intro 呢?每个实例是不是都带着一份?不是。看这几行:
console.log(Object.hasOwn(a, "intro"));
console.log(a.intro === b.intro);
console.log(Object.getPrototypeOf(a) === Student.prototype);false
true
trueintro 不属于 a 自己,a 和 b 读到的是同一个函数,它放在 Student.prototype 上。读取 a.intro 时,引擎先找 a 自身,没有,就顺着 a 的原型去找,在 Student.prototype 上找到了。数据各自一份,方法大家共用一份,这是类最基本的结构。

数据在实例里,方法在原型上;两个实例不共享数据,只共享方法。
类还有一个和普通函数不同的地方:它必须用 new 调用。
console.log(typeof Student);
try {
Student("小林");
} catch (error) {
console.log(`${error.name}: ${error.message}`);
}function
TypeError: Class constructor Student cannot be invoked without 'new'typeof 说明类本质上是一种函数;不带 new 调用则直接报错,不会像老式构造函数那样悄悄把属性写到全局或 undefined 上。
上面这个实验室可以让你反复创建实例、改某个实例的属性,再观察其他实例有没有受影响。先预测,再点,比光看效果有用。
第 8.1 题 · 单选题
constructor:实例怎样开始
new Order(...) 做的事可以拆成四步:造一个原型指向 Order.prototype 的空对象;让 constructor 里的 this 指向它;用传入的实参运行构造器代码;把这个对象作为结果返回。

构造器里写的 this.xxx = ...,就是在给第 1 步造出的那个对象加属性。
class Order {
status = "draft";
constructor(id, total = 0) {
this.id = id;
this.total = total;
}
summary() {
return `${this.id} / ${this.status} / ${this.total}`;
}
}
const one = new Order("A001", 68);
const two = new Order("A002");
console.log(one.summary());
console.log(two.summary());
console.log(Object.keys(one).join(","));A001 / draft / 68
A002 / draft / 0
status,id,totalstatus = "draft" 是公共实例字段(public instance field)。对不继承任何类的基础类,实例字段在构造器代码体运行之前就已初始化,这就是 Object.keys 里 status 排在最前面的原因。第二个订单没传 total,默认参数补成了 0。
没有默认值的参数也不会因为少传而报错,它的值就是 undefined:
class Person {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
}
const person = new Person("小满");
console.log(person.firstName, person.lastName);小满 undefined一个类里只能有一个 constructor,写两个是语法错误。想支持多种初始化方式,可以用默认参数、传一个选项对象,或者后文要讲的静态工厂方法。没有特殊初始化需求时可以干脆不写:基础类会得到一个空构造器,派生类会得到一个把参数原样交给父类的构造器。
this 不是类,也不是永远指着某个对象的变量。在构造器里,以及通过 instance.method() 调用的方法里,它指向当前实例;调用方式一变,this 就可能变,下一节马上看到。
第 8.2 题 · 多选题 · 选出所有正确项
实例方法与 this
类体里的普通方法不用写 function,方法之间用 this 互相调用:
class Person {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
fullName() {
return `${this.firstName} ${this.lastName}`;
}
greet(prefix = "你好") {
return `${prefix},我是 ${this.fullName()}`;
}
}
const p1 = new Person("林", "晓");
const p2 = new Person("周", "远");
console.log(p1.greet());
console.log(p2.greet("欢迎"));
console.log(Object.hasOwn(p1, "firstName"), Object.hasOwn(p1, "greet"));
console.log(p1.greet === p2.greet);你好,我是 林 晓
欢迎,我是 周 远
true false
true成员的位置可以这样归纳:
两个实例调用同一个 greet,结果不同,原因全在 this:它由“这次是谁调用的”决定,而不是由方法写在哪决定。
把方法取出来,this 就丢了
类体默认运行在严格模式下。把依赖 this 的方法赋给变量再单独调用,前面的点号没了,this 也就成了 undefined:
class Timer {
seconds = 0;
tick() {
this.seconds += 1;
return this.seconds;
}
}
const t = new Timer();
const tick = t.tick;
try {
tick();
} catch (error) {
console.log(`${error.name}: ${error.message}`);
}
const bound = t.tick.bind(t);
console.log(bound(), bound());TypeError: Cannot read properties of undefined (reading 'seconds')
1 2bind(t) 返回一个永远把 this 当作 t 的新函数。把方法交给定时器、事件监听或数组方法的回调时,这个问题最容易冒出来。另一种常见做法是把方法写成带箭头函数的字段:
class Counter {
count = 0;
inc = () => {
this.count += 1;
return this.count;
};
}
const c = new Counter();
const inc = c.inc;
console.log(inc(), inc());
console.log(Object.hasOwn(c, "inc"));1 2
true箭头函数没有自己的 this,字段初始化时它捕获了正在创建的实例,所以拿走也不会丢。代价是它成了每个实例自己的一份函数,不在原型上,不能被子类用 super.inc() 访问,创建大量实例时也多占内存。需要把方法当回调传出去的少数方法才这样写,其余方法保持普通写法。
第 8.3 题 · 单选题
第 8.4 题 · 判断题
getter、setter 与私有字段
如果外面的代码能随便把余额写成负数、把进度写成 "abc",对象迟早会处在一个不合法的状态。办法是把真正的数据放进私有字段,只开一个会校验的入口。
私有字段以 # 开头,必须先在类体里声明:
class Wallet {
#balance = 0;
constructor(owner, opening = 0) {
this.owner = owner;
this.balance = opening;
}
get balance() {
return this.#balance;
}
set balance(value) {
if (!Number.isFinite(value) || value < 0) {
throw new RangeError("余额必须是非负数字");
}
this.#balance = value;
}
}
const wallet = new Wallet("小夏", 120);
console.log(wallet.owner, wallet.balance);
console.log(Object.keys(wallet), JSON.stringify(wallet));
try {
wallet.balance = -5;
} catch (error) {
console.log(`${error.name}: ${error.message}`);
}小夏 120
[ 'owner' ] {"owner":"小夏"}
RangeError: 余额必须是非负数字wallet.balance 写起来像普通属性,读取时执行 get balance(),赋值时执行 set balance(value),所以不要写成 wallet.balance()。构造器里的 this.balance = opening 同样经过 setter,创建和以后修改共用同一条校验规则,不会出现“构造时能绕过检查”的漏洞。
两个细节值得留意。其一,私有字段不是 Object.keys 能看到的属性,JSON.stringify 也不会输出它,序列化时余额会丢,要输出得自己写方法。其二,只有 getter 没有 setter 就是只读属性,赋值在严格模式(包括类体内)下报 TypeError,在非严格代码里则被悄悄忽略。
#balance 是语言级的私有,不是靠命名约定。在类外写 wallet.#balance 是语法错误,连运行都到不了;而 wallet["#balance"] 读的是一个名字碰巧叫 "#balance" 的普通属性,得到 undefined,和私有字段毫无关系。

外部只能碰到访问器,私有字段和校验规则都留在类内部。
在这个交互里往校验门输入各种值,看哪些能通过、哪些被拒绝,并留意被拒绝时内部的值有没有变化。
第 8.5 题 · 多选题 · 选出所有正确项
static:属于类本身的成员
有些操作用不着某个具体实例。比如“根据完成数和总数造一个进度对象”,只需要两个数字,没必要先有一个进度对象才能调用。这类成员用 static 声明:
class LessonProgress {
static unit = "%";
static fromDone(done, total) {
return new LessonProgress(Math.round((done / total) * 100));
}
constructor(value) {
this.value = value;
}
label() {
return `${this.value}${LessonProgress.unit}`;
}
}
const progress = LessonProgress.fromDone(3, 4);
console.log(progress.label());
console.log(progress.fromDone);
console.log(LessonProgress.unit);75%
undefined
%三个位置现在可以分清了:progress.value 是实例自己的数据;progress.label() 是实例通过原型找到的方法;LessonProgress.fromDone() 和 LessonProgress.unit 挂在类上,实例上根本没有,所以 progress.fromDone 是 undefined。

遇到“这个东西找不到”的问题,先问它放在这三处的哪一处,再看你是从哪里去读它。
判断一个成员该不该加 static,只问一件事:它是否要用某个实例的状态。工厂方法、纯工具函数、类级别的配置和计数器适合放在类上;读取或修改实例数据的方法不适合。静态方法里的 this 指向调用它的类,而不是实例。
static 也可以私有。下面用一个私有静态字段做计数器,外面既改不了它,也读不到:
class Ticket {
static #issued = 0;
static next() {
Ticket.#issued += 1;
return Ticket.#issued;
}
}
console.log(Ticket.next(), Ticket.next());1 2第 8.6 题 · 单选题
extends 与 super:继承
两个概念之间确实是“子类是一种父类”,而且父类的行为稳定、值得共用,才考虑 extends。计时任务是一种任务,只是多了预计时长:
class Task {
constructor(title) {
this.title = title;
}
describe() {
return `任务:${this.title}`;
}
static kind() {
return "普通任务";
}
}
class TimedTask extends Task {
constructor(title, minutes) {
super(title);
this.minutes = minutes;
}
describe() {
return `${super.describe()},预计 ${this.minutes} 分钟`;
}
static kind() {
return `计时版 / ${super.kind()}`;
}
}
const task = new TimedTask("复习 class", 25);
console.log(task.describe());
console.log(task instanceof TimedTask, task instanceof Task);
console.log(Object.getPrototypeOf(TimedTask.prototype) === Task.prototype);
console.log(Object.getPrototypeOf(TimedTask) === Task);
console.log(TimedTask.kind());任务:复习 class,预计 25 分钟
true true
true
true
计时版 / 普通任务逐处对照:extends Task 让 TimedTask.prototype 的原型成为 Task.prototype,实例因此找得到父类的方法;构造器里的 super(title) 运行父类构造器,把 title 初始化好;子类写同名的 describe() 会遮住父类那个,需要时用 super.describe() 回头调用父类的版本;静态方法也能继承并用 super.kind() 调用,因为 TimedTask 这个函数自己的原型就是 Task(第四行输出)。

实例走上面一条链找方法,类本身走下面一条链找静态成员。
super() 必须先于 this
在子类自己写的构造器里,父类那一部分的实例是由 super(...) 造出来的。在它完成之前碰 this 会直接抛 ReferenceError:
class ChildTask extends Task {
constructor(title) {
try {
this.ready = true;
} catch (error) {
console.log(error.name);
}
super(title);
this.ready = true;
}
}
new ChildTask("演示");ReferenceError所以派生类构造器的习惯顺序是:先 super(...),再用 this。如果子类完全不写构造器,引擎替你补的就是 constructor(...args) { super(...args); },参数会原样传给父类:
class PlainTask extends Task {}
console.log(new PlainTask("默认构造器").describe());任务:默认构造器父类的私有字段会出现在子类实例里,但子类代码不能直接写 this.#名字,那个名字只在父类的类体内可见。子类想用父类的这部分状态,就得由父类提供公开的方法或访问器。
继承也不是复用代码的唯一办法,更不是第一选择。“购物车里有商品”是包含关系,让 Cart 持有一组 Product 对象很自然;写 Cart extends Product 就把关系搞反了,购物车会莫名其妙获得商品的所有方法。判断时可以把两个名字放进“A 是一种 B”这句话里读一遍,读不通就别继承。
用继承链浏览器点开几个类,核对每个实例的方法是从哪一层找到的,再和上面的示意图对照。
第 8.7 题 · 多选题 · 选出所有正确项
第 8.8 题 · 判断题
原型链:属性查找与 instanceof
类是语法,共享方法和继承的真正机制仍是原型。以 task 为例,读一个属性时的查找路径是:
task
→ TimedTask.prototype
→ Task.prototype
→ Object.prototype
→ null引擎一旦在某层找到名字就停下。在实例上写一个和原型同名的属性,只会遮蔽(shadow)原型上的那个,不会改动原型。
直接往 prototype 上加东西
类声明之后,prototype 依然是个可以改的普通对象。旧代码和一些兼容层会这样扩展:
class Person {
constructor(name) {
this.name = name;
}
}
Person.prototype.role = "学员";
Person.prototype.introduce = function () {
return `${this.role}:${this.name}`;
};
const m = new Person("阿宁");
const n = new Person("小越");
n.role = "助教";
console.log(m.introduce());
console.log(n.introduce());
console.log(Object.hasOwn(m, "role"), Object.hasOwn(n, "role"));学员:阿宁
助教:小越
false truem 自己没有 role,读到的是原型上的默认值;n.role = "助教" 在 n 自身新建了属性,原型上的“学员”没动,m 当然不受影响。
这种写法能自己控制的类,就直接把方法写进类体;更别去改 Object.prototype、Array.prototype 这类内置原型,加进去的名字会出现在整个运行环境所有对象的查找路径上,容易跟第三方库和将来的标准撞车。
给原型添加方法时有个特别容易犯的错:为了少打 function 而用箭头函数。
Person.prototype.wrongName = () => this.name;箭头函数的 this 来自它被定义时所处的外层,不是 m.wrongName() 里点号前的那个对象,所以这里取不到实例的 name。需要动态 this 的方法,请写成普通方法或普通函数。
class 与老式构造函数
类和构造函数都能做出“实例存数据,原型存方法”的结构:
class Box {
constructor(value) {
this.value = value;
}
getValue() {
return this.value;
}
}
function OldBox(value) {
this.value = value;
}
OldBox.prototype.getValue = function () {
return this.value;
};
const box = new Box(42);
const old = new OldBox(42);
console.log(box.getValue(), old.getValue());
console.log(Object.getPrototypeOf(box) === Box.prototype);
console.log(Box.prototype.constructor === Box);
console.log(Object.keys(Box.prototype), Object.keys(OldBox.prototype));42 42
true
true
[] [ 'getValue' ]但类不是构造函数的简单换写。除了前面见过的“必须用 new”,类体默认是严格模式;类体里的方法是不可枚举的(上面最后一行:Box.prototype 没有可枚举键,手写赋值的 OldBox.prototype 有),这让 for...in 遍历实例时不会混进方法;类声明和 let 一样有暂时性死区,初始化之前使用会抛 ReferenceError:
try {
new Seat();
} catch (error) {
console.log(`${error.name}: ${error.message}`);
}
class Seat {}ReferenceError: Cannot access 'Seat' before initialization把类声明写在第一次使用之前,依赖顺序也更好读。
instanceof 问的是:右边构造器的 prototype,有没有出现在左边对象的原型链上?它看的是原型关系,不看对象有没有同名属性:
const fake = { title: "冒牌", describe() {} };
const real = Object.create(Task.prototype);
console.log(fake instanceof Task);
console.log(real instanceof Task);false
truefake 属性长得和任务一样却不是任务;real 没经过构造器,只要原型链上有 Task.prototype,instanceof 就认。
第 8.9 题 · 单选题
第 8.10 题 · 判断题
常见问题:先看成员在哪,再看怎么调用
类相关的错误多半有规律可循:先判断成员放在哪一层,再看代码是以什么方式调用它的。
第 8.11 题 · 多选题 · 选出所有正确项
综合实践:可校验的任务看板
把本章的能力合起来做一个小模型。看板里有普通任务和计时任务;每项任务有自动编号、负责人和受控的进度,计时任务的说明里还要有预计分钟数。
功能要求
- 创建
WorkItem,用静态字段nextId给每个实例生成递增编号。 - 构造器接收
title和owner,初始进度为0。 - 用私有字段保存进度,提供
progress的 getter 和 setter。 - setter 只接受
0到100之间的有限数字,否则抛出RangeError。 - 实现
describe(),返回编号、标题、负责人和进度。 - 创建
TimedWorkItem extends WorkItem,构造器多接收一个minutes。 - 子类覆盖
describe(),并用super.describe()复用父类的结果。 - 创建至少两个实例,修改进度并打印结果。
可以从这个骨架开始:
class WorkItem {
static nextId = 1;
#progress = 0;
constructor(title, owner) {
// 生成 id,保存 title 和 owner
}
get progress() {
// 返回私有进度
}
set progress(value) {
// 校验后更新私有进度
}
describe() {
// 返回任务说明
}
}
class TimedWorkItem extends WorkItem {
// 补全构造器,覆盖 describe
}验收标准
完成后,下面的测试代码应该能跑通:
const reading = new WorkItem("阅读类语法", "小林");
const coding = new TimedWorkItem("完成类练习", "小周", 45);
reading.progress = 100;
coding.progress = 60;
console.log(reading.describe());
console.log(coding.describe());
console.log(coding instanceof TimedWorkItem, coding instanceof WorkItem);
try {
coding.progress = 120;
} catch (error) {
console.log(error.name);
}符合要求的输出:
#1 阅读类语法 / 小林 / 100%
#2 完成类练习 / 小周 / 60% / 预计 45 分钟
true true
RangeError先自己想一想,再看一种完整实现
一种完整实现已经藏好了,准备好再点开
继续挑战
- 加一个只读 getter
done,进度等于100时返回true; - 加静态工厂
WorkItem.from(data),根据普通对象创建实例; - 新增
UrgentWorkItem,覆盖describe()并显示优先级; - 想一想“标签”该继承任务,还是作为数组存在任务里,并写下理由。
本章自测
第 8.12 题 · 单选题
第 8.13 题 · 多选题 · 选出所有正确项
第 8.14 题 · 填空题
第 8.15 题 · 判断题
第 8.16 题 · 单选题
第 8.17 题 · 多选题 · 选出所有正确项
总结
class把一批对象的初始化规则和共享行为集中描述,new每次造出一个独立实例。- 构造器里通过
this写入的属性和公共字段在实例上;普通方法、getter、setter 在prototype上,由实例共享。 #私有字段是语言级的私有,配合 getter/setter 可以把校验放在唯一入口。static成员属于类本身,适合工厂方法、工具函数、类级配置和计数器。extends表示“是一种”;派生构造器先super(...)再用this,子类可以覆盖方法,也可用super.method()复用父类实现。- 属性读取沿“实例 → 子类原型 → 父类原型 →
Object.prototype→null”查找,instanceof看的正是这条链。 - 把方法当回调传出去要留意
this;“有一个”关系用属性保存,不要硬套继承。