所属板块:3. 原型与面向对象(OOP)
记录日期:2026-03-xx
更新:遇到 class / extends / super 相关题或源码阅读时补充
1. class 语法糖的本质
ES6 的 class 只是一层语法糖,底层依然是 [3-1] 里的原型链 + [3-2] 的构造函数机制。
关键事实:
class Person {}
console.log(typeof Person); // "function"
console.log(Person.prototype); // { constructor: Person }
class 只是让代码写起来更像传统 OOP,但本质上还是函数 + prototype。
2. class 与 ES5 构造函数的严格差异(高频考点)
-
默认开启严格模式
class内部自动 "use strict",this 指向问题更严格。 -
不存在变量提升(TDZ)
const p = new Person(); // ReferenceError(TDZ) class Person {} -
必须用 new 调用
直接当普通函数调用会报错(内部有[[IsClassConstructor]]标记)。 -
方法默认不可枚举
const keys = Object.keys(Person.prototype); // [](不像 ES5 那样会枚举)
3. extends 与 super 的双重继承魔法
extends 不只是继承原型,还做了两件事:
- 子类原型继承父类原型(实例方法)
- 子类本身(作为函数)继承父类本身(静态方法)
class Parent {
static staticMethod() { console.log("静态方法"); }
}
class Child extends Parent {}
Child.staticMethod(); // 可以直接调用(继承静态方法)
super 的两种用法(非常容易混):
-
作为函数调用(必须在子类 this 之前)
constructor(name) { super(name); // 调用父类构造函数 this.age = 18; } -
作为对象使用
- 普通方法里:
super.say()→ 指向父类原型 - 静态方法里:
super.staticMethod()→ 指向父类本身
- 普通方法里:
4. 类型检测的闭环
instanceof底层:顺着原型链查找(与 [3-1] 原型链机制一致)Object.prototype.isPrototypeOf():更直接的原型判断Object.getPrototypeOf()/Object.setPrototypeOf():现代推荐操作方式
示例:
const c = new Child();
console.log(c instanceof Parent); // true
console.log(Parent.prototype.isPrototypeOf(c)); // true
5. 小结 & 第三板块完结
class+extends+super本质还是 [3-1] 原型链 + [3-2] new + [3-3] 寄生组合式继承的语法糖- 掌握了 ES5 的原型继承,再看 class 源码会非常轻松
- [3-1] 到 [3-4] 四个部分,共同构成了 JS 面向对象的完整体系(从原型三角 → 对象创建 → 继承演进 → 现代语法)
第三板块(原型与面向对象)到此全部结束。
这是 JS 最具“哲学意味”的部分,彻底吃透后看 Vue/React 源码会顺很多。
返回总目录:戳这里