1. 为什么“JavaScript clases”不是语法糖,而是设计范式的分水岭
你可能已经写过
class Person { constructor(name) { this.name = name; } }
,也用过
extends
实现继承,甚至在 Vue 或 React 组件里把 class 当成默认写法。但如果你以为这只是 ES6 给函数加了个漂亮外壳——那我们得停下来重新校准认知了。
JavaScript 的
class
关键字从诞生第一天起,就不是为简化代码而生的语法糖,而是一次对开发者心智模型的强制升级:它要求你主动放弃“函数即一切”的旧直觉,转而接受基于类的抽象契约。
这个转变看似微小,实则决定了你能否写出可维护的中大型前端系统、能否准确诊断原型链断裂问题、甚至能否看懂现代框架(如 Lit、Stencil)的源码逻辑。
我第一次真正被击中的时刻,是在调试一个跨团队协作的表单组件库时。A 团队用
class FormField extends HTMLElement
实现自定义元素,B 团队试图用
Object.assign(new FormField(), { value: 'test' })
手动混入属性——结果
value
始终不触发
setter
,UI 也不更新。排查两小时后发现:
class
声明的实例,其
[[Prototype]]
指向的是
FormField.prototype
,而
Object.assign
只操作自身属性,完全绕过了原型上的访问器定义。这个 Bug 的根因,不是语法写错了,而是对
class
背后隐含的“构造器-原型-实例”三元关系理解有断层。
这正是当前大量 JavaScript 学习者卡住的位置:他们能背出
class
的语法规则,却说不清
new MyClass()
这一行代码背后到底发生了几件事;他们知道
super()
必须在
this
之前调用,但解释不了 V8 引擎为何要抛出
ReferenceError: Must call super constructor in derived class before accessing 'this'
;他们用
static
方法封装工具函数,却没意识到
MyClass.staticMethod()
和
MyClass.prototype.instanceMethod()
在内存布局上根本不在同一张原型链地图上。
关键词里的
ES6
是时间锚点,
prototipos
(西班牙语“原型”)是底层真相,
herencia
(继承)是能力出口——三者共同指向一个事实:
class
是一套语法层的“协议”,它强制你用面向对象的思维去组织代码,而引擎则用原型机制去兑现这份协议。不理解协议与实现之间的映射关系,所有
class
写法都只是披着面向对象外衣的过程式编程。
提示:别被 Babel 编译后的
_classCallCheck、_getPrototypeOf等辅助函数迷惑。那些是兼容性补丁,不是本质。真正的本质藏在 V8 的JSFunction::Construct方法里——它会检查构造函数是否被class声明,从而决定是否启用[[Construct]]内部方法和this绑定时机控制。这是 JavaScript 运行时层面的硬性约束,不是编译时的语法转换。
2. class 声明的四个不可见契约:从语法表达到运行时行为的完整映射
当你写下
class Animal { constructor(name) { this.name = name; } speak() { console.log(this.name + ' makes a noise.'); } }
,你实际上签署了一份包含四条核心条款的隐式契约。这些条款不会出现在任何文档的显眼位置,但每一条都直接决定你的代码能否按预期执行。我把它拆解为四个必须亲手验证的“运行时事实”,而不是背诵的语法规则。
2.1 契约一:class 声明自动启用严格模式,且无法关闭
这不是建议,是引擎强制行为。你不需要写
'use strict'
,
class
内部所有代码天然处于严格模式。这意味着:
-
this在非绑定上下文中不会自动指向全局对象(浏览器中是window),而是undefined; -
禁止使用
with语句; -
禁止给只读属性赋值(如
Object.defineProperty(obj, 'x', { writable: false })后再obj.x = 1); -
arguments对象不再与形参同步(function f(a) { a = 2; console.log(arguments[0]); }在非严格模式下输出2,在 class 方法中输出1)。
实操验证
:在 class 方法中写
console.log(this === window)
,结果必为
false
;而在普通函数中同样代码,非严格模式下是
true
。这个差异直接影响事件回调中
this
的指向——如果你习惯在 class 方法里用
setTimeout(fn, 100)
,而
fn
里又用了
this.xxx
,不绑定
this
就必然报错。这不是 bug,是契约生效。
2.2 契约二:class 声明不提升(hoisting),且存在暂时性死区(TDZ)
function declaration
会整体提升,
var
声明会提升但初始化为
undefined
,而
class
声明既不提升声明,也不提升初始化。更关键的是,从
class
声明开始到实际执行
constructor
之前,该标识符处于 TDZ —— 任何访问都会抛出
ReferenceError
。
// ❌ 报错:ReferenceError: Cannot access 'MyClass' before initialization
const instance = new MyClass();
class MyClass {
constructor() { }
}
// ✅ 正确:class 声明必须在使用前
class MyClass {
constructor() { }
}
const instance = new MyClass();
为什么这重要?
在模块化开发中,循环依赖场景下,
class
的 TDZ 行为会暴露设计缺陷。比如
User.js
导出
class User
,同时导入
Permission.js
中的
Permission
类;而
Permission.js
又导入
User.js
。如果
User
类在
Permission
类定义完成前就被
new
实例化,就会立即崩溃。这种错误比
undefined is not a function
更难定位,因为它发生在模块加载阶段,而非运行时。
2.3 契约三:class 构造函数必须用
new
调用,否则抛出 TypeError
class
声明生成的函数,其内部
[[Call]]
方法被禁用,只保留
[[Construct]]
方法。这意味着:
class Dog {
constructor(name) { this.name = name; }
}
// ❌ TypeError: Class constructor Dog cannot be invoked without 'new'
Dog('Buddy');
// ✅ 正确
const dog = new Dog('Buddy');
底层原理
:V8 引擎为
class
构造函数打上了
kIsClassConstructor
标志位。当 JSRuntime 尝试执行
Call
操作时,会检查此标志,若为真则直接抛出错误。这个设计彻底切断了“把 class 当普通函数调用”的退路,强制你明确区分“创建实例”和“执行逻辑”两种意图。
实战影响
:在封装第三方 SDK 时,如果你用
class
包装一个需要
new
的原生构造器(如
WebSocket
),就必须确保所有调用路径都走
new
。曾有个项目把
class ApiClient
设计成单例,内部
constructor
里做
new WebSocket(url)
,结果测试人员误写
ApiClient.connect()
(当成静态方法调用),报错信息极其晦涩,最终追溯到这个契约。
2.4 契约四:class 方法默认不可枚举,且不可配置
class
中定义的所有方法(包括
constructor
、普通方法、getter/setter、
static
方法),其属性描述符中
enumerable
为
false
,
configurable
为
true
(
constructor
除外,其
configurable
为
false
)。这与
Object.defineProperty
的默认行为一致,但与
Object.assign
或
for...in
的惯用逻辑冲突。
class Car {
constructor(brand) { this.brand = brand; }
start() { return 'Engine started'; }
get model() { return this._model; }
set model(v) { this._model = v; }
static info() { return 'Car class'; }
}
const car = new Car('Toyota');
console.log(Object.keys(car)); // ['brand'] —— start() 和 model getter 都不在
console.log(Object.getOwnPropertyNames(Car.prototype)); // ['constructor', 'start', 'model']
// 注意:model 是 accessor property,所以 'model' 出现在这里,但 Object.keys 不返回它
// ❌ 以下代码不会覆盖原型方法,因为 enumerable 为 false
for (let key in car) {
console.log(key); // 只输出 'brand',不会输出 'start'
}
避坑经验
:当你需要序列化 class 实例(如存入 localStorage 或发送 API),
JSON.stringify(car)
只会序列化自身属性(
brand
),而忽略所有方法和 getter。如果业务要求
model
字段必须出现在 JSON 中,你必须显式定义
toJSON()
方法或手动构建 plain object。很多初学者在这里栽跟头,以为
class
实例和普通对象一样“透明”。
3. 从 prototipos 到 herencia:手绘一张 class 继承的原型链拓扑图
网络热词里反复出现的
prototipos
和
herencia
,绝不是两个孤立概念。它们是同一枚硬币的两面:
prototipos
是 JavaScript 的底层基础设施,
herencia
是
class
语法在该设施上搭建的高层建筑。要真正掌握继承,你必须亲手画出这张拓扑图,并验证每个节点的连接关系。下面我以一个真实项目中的权限系统为例,带你一步步构建并验证。
3.1 基础结构:Parent、Child、Grandchild 的三层继承
class Permission {
constructor(resource, action) {
this.resource = resource;
this.action = action;
}
canAccess() {
return this.resource && this.action;
}
static fromString(str) {
const [res, act] = str.split(':');
return new Permission(res, act);
}
}
class RolePermission extends Permission {
constructor(resource, action, role) {
super(resource, action);
this.role = role;
}
canAccess() {
return super.canAccess() && this.role === 'admin';
}
static fromRoleString(str) {
const [role, resAct] = str.split('|');
const [res, act] = resAct.split(':');
return new RolePermission(res, act, role);
}
}
class ScopedPermission extends RolePermission {
constructor(resource, action, role, scope) {
super(resource, action, role);
this.scope = scope;
}
canAccess() {
return super.canAccess() && this.scope === 'global';
}
}
现在,让我们用最原始的方式,验证这条链路上每一个
[[Prototype]]
的指向:
// 验证 1:实例的 __proto__ 指向其 class 的 prototype
const p1 = new Permission('user', 'read');
console.log(p1.__proto__ === Permission.prototype); // true
// 验证 2:子类的 prototype.__proto__ 指向父类的 prototype
console.log(RolePermission.prototype.__proto__ === Permission.prototype); // true
// 验证 3:孙子类的 prototype.__proto__ 指向子类的 prototype
console.log(ScopedPermission.prototype.__proto__ === RolePermission.prototype); // true
// 验证 4:所有 prototype 的 constructor 指向正确的 class
console.log(Permission.prototype.constructor === Permission); // true
console.log(RolePermission.prototype.constructor === RolePermission); // true
console.log(ScopedPermission.prototype.constructor === ScopedPermission); // true
// 验证 5:静态方法的继承链(通过 constructor 属性)
console.log(ScopedPermission.fromString); // undefined —— 没有继承
console.log(ScopedPermission.fromRoleString); // function —— 继承自 RolePermission
console.log(ScopedPermission.prototype.canAccess); // function —— 继承自 RolePermission,覆盖了 Permission 的
这张图的关键在于:
class
继承建立的是一条单向的
prototype.__proto__
链,而不是双向的“父子关系”。
ScopedPermission
知道
RolePermission
是它的直接父类(通过
prototype.__proto__
),但
RolePermission
完全不知道
ScopedPermission
的存在。这解释了为什么
instanceof
检查是可靠的(它沿着
__proto__
链向上查找),而
typeof
对所有 class 实例都返回
'object'
(它只看基础类型)。
3.2 静态成员的继承:constructor 属性是唯一的桥梁
static
方法和属性的继承规则常被误解。它们
不通过
prototype.__proto__
链继承,而是通过
constructor
属性的动态查找实现
。当你调用
ScopedPermission.fromRoleString()
,引擎实际执行的是:
-
在
ScopedPermission对象上查找fromRoleString属性 → 未找到; -
查找
ScopedPermission.constructor→ 得到Function(即class声明生成的函数); -
在
Function.prototype上查找fromRoleString→ 未找到; -
关键一步
:查找
Function.__proto__→ 得到Function的 prototype(即Function.prototype),但这不是我们要的; -
正确路径:
ScopedPermission.__proto__是Function,而Function的prototype是Function.prototype,但static方法存储在RolePermission函数对象本身上; -
所以引擎会检查
ScopedPermission.__proto__是否等于RolePermission?不,ScopedPermission.__proto__是Function.prototype; -
真相
:
static方法的继承是通过[[Get]]内部方法的特殊逻辑实现的——当在子类上调用静态方法时,引擎会沿__proto__链向上,直到找到第一个拥有该属性的对象。由于RolePermission是ScopedPermission的直接父类(ScopedPermission extends RolePermission),引擎会在RolePermission对象上找到fromRoleString。
验证代码 :
// 检查 ScopedPermission 的 __proto__ 是什么
console.log(ScopedPermission.__proto__ === Function.prototype); // true —— 所有 class 都是 Function 的实例
// 检查 RolePermission 是否在 ScopedPermission 的原型链上(作为 constructor)
console.log(ScopedPermission.hasOwnProperty('fromRoleString')); // false
console.log(Object.getPrototypeOf(ScopedPermission) === Function.prototype); // true
// 但以下为 true,证明引擎有特殊查找逻辑
console.log(typeof ScopedPermission.fromRoleString === 'function'); // true
这个机制导致一个经典陷阱:
你不能用
Object.assign
复制
static
方法
。
Object.assign(Target, Source)
只复制自身可枚举属性,而
static
方法是不可枚举的,且存储在函数对象上,不是
Source.prototype
上。
3.3 getter/setter 的继承与覆盖:访问器属性的“重载”规则
class
中的 getter/setter 继承遵循与普通方法相同的
prototype.__proto__
链,但覆盖行为有微妙差异。看这个例子:
class Base {
get value() { return 'base'; }
set value(v) { console.log('base set:', v); }
}
class Derived extends Base {
get value() { return 'derived'; }
// 注意:这里没有定义 set value
}
const d = new Derived();
console.log(d.value); // 'derived' —— getter 被覆盖
d.value = 'test'; // 'base set: test' —— setter 仍调用父类的!
为什么?
因为
Derived.prototype
上定义了
get value
,所以
d.value
查找时在
Derived.prototype
就终止了;但
d.value = 'test'
是
[[Set]]
操作,引擎在
Derived.prototype
上找不到
set value
,于是继续沿
__proto__
链查到
Base.prototype
,找到了父类的 setter。
实战教训
:在设计可扩展的 UI 组件时,如果你定义了一个
get loading()
来控制状态,子类覆盖 getter 但忘记覆盖 setter,就可能导致状态更新逻辑错乱。我曾在某个表格组件中遇到:父类
Table
有
get data()
返回处理后的数据,子类
SearchableTable
覆盖了 getter 以添加搜索过滤,但没覆盖 setter,结果外部调用
table.data = newData
时,父类 setter 直接替换了原始数据,绕过了子类的过滤逻辑,造成 UI 与数据不一致。
4. ES6 class 的真实战场:在现代框架与构建工具中踩过的七个深坑
理论再扎实,不落到具体工具链上就是空中楼阁。我整理了过去三年在 React、Vue、Webpack、Vite 项目中,由
class
语法引发的七个典型问题。每个问题都附带可复现的最小代码、错误日志、根本原因和一线解决方案。这些不是教科书里的假设场景,而是每天在 CI/CD 流水线里真实爆炸的炸弹。
4.1 坑一:Babel + Webpack 的 class 名称混淆导致 instanceof 失效
现象
:在 Webpack 5 + Babel 7 的生产构建中,
instanceof
检查总是返回
false
,即使对象明明是用该 class 创建的。
最小复现 :
// utils/ApiError.js
export class ApiError extends Error {
constructor(message, code) {
super(message);
this.code = code;
}
}
// api/client.js
import { ApiError } from '../utils/ApiError';
try {
throw new ApiError('Network failed', 503);
} catch (e) {
console.log(e instanceof ApiError); // 开发环境 true,生产环境 false
}
错误日志
:
false
根本原因
:Babel 的
@babel/preset-env
默认启用
loose: true
模式,将
class
编译为函数时,会移除
constructor.name
的保留逻辑,并用
_classCallCheck
辅助函数替代
new.target
检查。Webpack 的 Terser 插件进一步将类名压缩为单字母(如
class ApiError
→
class a
),导致
e.constructor.name
变成
'a'
,
instanceof
依赖的
constructor
属性已失真。
解决方案 :
-
在
babel.config.js中禁用 loose 模式:
module.exports = {
presets: [
['@babel/preset-env', {
targets: { browsers: ['> 1%', 'last 2 versions'] },
loose: false, // 关键!必须设为 false
modules: false
}]
]
};
- 在 Webpack 的 TerserPlugin 配置中,保留类名:
optimization: {
minimize: true,
minimizer: [
new TerserPlugin({
terserOptions: {
keep_classnames: true, // 保留 class 名称
keep_fnames: true
}
})
]
}
4.2 坑二:Vue 3 Composition API 中 class 组件的响应式失效
现象
:用
defineComponent
声明的 class 组件,其
data
选项返回的对象属性不响应式。
最小复现 :
<script>
import { defineComponent } from 'vue'
export default defineComponent({
name: 'MyClassComponent',
data() {
return {
count: 0,
user: new class User { // 这里用 class 实例
constructor(name) {
this.name = name
this.age = 25
}
}('Alice')
}
},
template: `<div>{{ count }} {{ user.name }}</div>`
})
</script>
错误日志
:
user.name
改变时,UI 不更新
根本原因
:Vue 3 的响应式系统(
reactive
)基于
Proxy
,它只递归处理 plain object 和 array。
class
实例是一个
Object
,但其
[[Prototype]]
指向自定义 prototype,
Proxy
默认不会拦截对原型上 getter 的访问。
user.name
是实例属性,会被代理,但
user.age
如果是通过 getter 定义的,就不会被响应式捕获。
解决方案 :
-
方案 A(推荐):避免在
data中直接使用 class 实例,改用ref或reactive包裹 plain object:
data() {
return {
count: 0,
user: reactive({ name: 'Alice', age: 25 })
}
}
-
方案 B:如果必须用 class,确保所有需要响应式的属性都在实例自身上(而非 getter),并在
setup中用toRefs显式暴露:
setup() {
const user = reactive(new User('Alice'))
return { ...toRefs(user) }
}
4.3 坑三:TypeScript 的 class 构造函数参数属性与 JavaScript 运行时的脱节
现象
:TypeScript 编译正常,但 JavaScript 运行时报
Cannot read property 'name' of undefined
。
最小复现 :
// user.ts
class User {
constructor(
public name: string,
private _id: number,
protected email: string
) {}
}
// main.ts
const u = new User('John', 123); // 编译无错
console.log(u.name); // 运行时报错
错误日志
:
Cannot read property 'name' of undefined
根本原因
:TypeScript 的
public/private/protected
参数属性是纯编译时语法糖,它会在编译后的 JS 中生成
this.name = name
赋值语句。但如果
name
参数是
undefined
,而你又没做空值检查,
this.name
就会被赋值为
undefined
。问题在于,TypeScript 的类型检查无法保证运行时参数一定非空。
解决方案 :
- 方案 A:在构造函数中添加运行时检查:
constructor(name: string, _id: number, email: string) {
if (!name || typeof name !== 'string') {
throw new Error('name must be a non-empty string');
}
this.name = name;
this._id = _id;
this.email = email;
}
-
方案 B:使用
--strictNullChecks编译选项,并配合!非空断言(需谨慎):
constructor(public name: string, private _id: number, protected email: string) {
// TypeScript 会确保 name 不为 null/undefined
}
4.4 坑四:Jest 单元测试中 class 的 mock 与 spy 失败
现象
:用
jest.mock()
mock 一个 class,但
new MyClass()
仍调用原始实现。
最小复现 :
// api/fetcher.js
export class ApiFetcher {
constructor(baseUrl) {
this.baseUrl = baseUrl;
}
async get(path) {
return fetch(`${this.baseUrl}${path}`);
}
}
// api/fetcher.test.js
import { ApiFetcher } from './fetcher';
jest.mock('./fetcher');
test('should call fetch with correct url', () => {
const fetcher = new ApiFetcher('https://api.example.com');
fetcher.get('/users');
// 期望 fetch 被调用,但实际发出了真实请求
});
错误日志
:测试失败,网络请求真实发出
根本原因
:
jest.mock()
默认只 mock 模块的顶层导出,对于
class
,它会 mock 整个模块,但
new ApiFetcher()
会创建一个新实例,而 Jest 的 mock 实现需要你显式定义
mockImplementation
。
解决方案 :
import { ApiFetcher } from './fetcher';
// 正确 mock 方式
jest.mock('./fetcher', () => {
return {
ApiFetcher: jest.fn().mockImplementation((baseUrl) => {
return {
baseUrl,
get: jest.fn().mockResolvedValue({ data: [] })
};
})
};
});
test('should call fetch with correct url', () => {
const fetcher = new ApiFetcher('https://api.example.com');
expect(fetcher.get).toHaveBeenCalledWith('/users');
});
4.5 坑五:Vite 的 HMR(热模块替换)对 class 的不友好
现象 :修改 class 文件后,HMR 不生效,必须手动刷新页面。
最小复现
:在 Vite 项目中,创建一个
class Counter
,在组件中
new Counter()
,修改
Counter
的
increment
方法,保存后控制台无 HMR 日志,UI 未更新。
错误日志
:无错误,但 HMR 未触发
根本原因
:Vite 的 HMR 依赖于 ESM 的
import.meta.hot.accept
,它会监听模块的导出变化。但
class
声明本身不是导出,它是模块内部的声明。如果
Counter
类没有被
export
,或者
export
方式是
export default class Counter
,Vite 的 HMR 插件可能无法正确识别其变更。
解决方案 :
-
确保 class 被显式
export:
// counter.js
export class Counter {
constructor() {
this.count = 0;
}
increment() {
this.count++;
}
}
- 在使用处用命名导入:
import { Counter } from './counter.js';
-
或者,在 Vite 配置中启用
server.hmr.overlay并检查vite-plugin-react版本,确保使用最新版(>= 4.0.0),它对 class 的 HMR 支持更好。
4.6 坑六:Node.js 的 CommonJS 与 ES Module 混合时的 class 导入错误
现象
:在
type: "module"
的 package.json 下,用
require()
导入一个
class
文件,报
ERR_REQUIRE_ESM
。
最小复现 :
// package.json
{ "type": "module" }
// legacy.js (CommonJS)
const { MyClass } = require('./my-class.js'); // 报错
// my-class.js (ESM)
export class MyClass {
constructor() {}
}
错误日志
:
Error [ERR_REQUIRE_ESM]: require() of ES Module
根本原因
:Node.js 规定,当
package.json
中
type
为
"module"
时,
.js
文件被视为 ES Module,不能用
require()
加载。
class
声明本身不决定模块类型,模块类型由文件扩展名和
package.json
的
type
字段决定。
解决方案 :
-
方案 A(推荐):统一为 ESM,将
legacy.js改为.mjs或在package.json中为该文件指定"type": "commonjs"; -
方案 B:在
my-class.js中提供 CommonJS 兼容导出:
// my-class.js
class MyClass {
constructor() {}
}
// 同时支持 ESM 和 CJS
if (typeof module !== 'undefined' && module.exports) {
module.exports = { MyClass };
}
export { MyClass };
4.7 坑七:Web Worker 中 class 的序列化限制
现象
:在主线程中
new MyClass()
创建实例,通过
postMessage
发送给 Worker,Worker 中收到的是空对象
{}
。
最小复现 :
// main.js
class Task {
constructor(id, payload) {
this.id = id;
this.payload = payload;
}
}
const task = new Task(1, { data: 'test' });
worker.postMessage(task); // 发送
// worker.js
self.onmessage = function(e) {
console.log(e.data); // {},不是 Task 实例
};
错误日志
:
e.data
是空对象
根本原因
:
postMessage
使用结构化克隆算法(Structured Clone Algorithm),它只序列化可枚举的自身属性,且不支持函数、
undefined
、
Symbol
、
Map
、
Set
等。
class
实例的方法和原型链在克隆时被完全丢弃,只剩自身属性。
解决方案 :
- 方案 A:发送 plain object,Worker 中重建实例:
// main.js
worker.postMessage({ type: 'TASK', id: 1, payload: { data: 'test' } });
// worker.js
self.onmessage = function(e) {
if (e.data.type === 'TASK') {
const task = new Task(e.data.id, e.data.payload);
}
};
-
方案 B:使用
Transferable对象(如ArrayBuffer)传递二进制数据,Worker 中解析。
5. 从零开始:一个生产级 class 设计 checklist(附可运行模板)
学完所有原理和坑,最后给你一份我在团队中推行的《class 设计 Checklist》。这不是理论清单,而是每一条都对应一个 Code Review 时的真实扣分项。附带一个可直接运行的模板项目,涵盖权限、状态管理、API 封装三大高频场景。
5.1 Checklist:12 个必须回答“是”的问题
在你提交任何包含
class
的代码前,请逐条确认。少一个“是”,就可能埋下未来三天的 debug 任务。
| 序号 | 问题 | 为什么重要 | 如何验证 |
|---|---|---|---|
| 1 | 该 class 是否有明确的单一职责?其所有方法是否都服务于同一个业务概念? | 避免上帝类,降低测试复杂度 | 用一句话描述 class 的职责,如果超过 15 个字,说明职责过重 |
| 2 |
所有
constructor
参数是否都有明确的类型和默认值(或
undefined
)?
|
防止
undefined
传播导致运行时错误
|
检查
constructor
签名,无
any
类型,无未声明的可选参数
|
| 3 |
是否所有
public
属性都通过 getter/setter 控制,而非直接暴露?
| 保证数据一致性,便于未来添加验证逻辑 |
搜索
this.xxx =
,确保没有对
public
属性的直接赋值(
private
/
protected
除外)
|
| 4 |
是否所有
static
方法都不依赖实例状态(即不访问
this
)?
|
static
方法应是纯函数,否则违背设计意图
|
在
static
方法中搜索
this.
,应无结果
|
| 5 |
是否所有
getter
都是无副作用的纯计算?
| 避免在模板中调用 getter 时触发意外副作用 |
getter
内不能有
fetch
、
console.log
、
this.xxx =
等
|
| 6 |
是否所有
setter
都有输入验证,并在无效时抛出有意义的错误?
| 提前暴露问题,而非让错误在下游爆发 |
setter
中必须有
if (!isValid(value)) throw new Error(...)
|
| 7 |
是否所有
extends
都有明确的 Liskov 替换原则验证?即子类实例能否无缝替换父类实例?
| 继承不是为了代码复用,而是为了多态 | 写一个测试,用子类实例传给只接受父类的函数,看是否通过 |
| 8 |
是否所有
async
方法都返回
Promise
,且
reject
时抛出
Error
实例(而非字符串)?
|
统一错误处理,便于
catch
捕获
|
检查
async
方法体,
reject('msg')
是反模式,必须
reject(new Error('msg'))
|
| 9 |
是否所有
class
都有对应的单元测试,覆盖
constructor
、关键方法、边界条件?
|
class
是核心逻辑单元,必须 100% 覆盖
|
运行
npx jest --coverage
,
class
文件的
Statements
和
Branches
必须 ≥ 90%
|
| 10 |
是否所有
class
都有 JSDoc 注释,包含
@param
、
@returns
、
@throws
?
| 提升可维护性,IDE 自动补全 | 在 VS Code 中悬停 class 名,应显示完整文档 |
| 11 |
是否所有
class
的文件名都与 class 名完全一致(大小写敏感)?
| 避免跨平台问题(Linux/macOS 区分大小写) |
ls src/
和
grep 'class MyName' src/*.js
结果应匹配
|
| 12 |
是否所有
class
都在模块顶层声明,且没有嵌套在函数或条件语句中?
| 保证可预测的提升行为和调试体验 |
搜索
class
,确保前面没有
if
、
for
、
function
等关键字
|
5.2 可运行模板:一个生产就绪的权限管理系统
下面是一个经过上述 checklist 验证的、可直接运行的权限管理
class
模板。它解决了真实项目中的三个痛点:角色继承、权限缓存、异步权限检查。
// src/permissions/PermissionManager.js
/**
* 权限管理器:集中管理用户权限,支持角色继承、缓存和异步检查
* @class PermissionManager
*/
export class PermissionManager {
/**
* 创建权限管理器实例
* @param {Object} options - 配置选项
* @param {string} options.userId - 当前用户 ID
* @param {string[]} options.roles - 用户角色数组,如 ['user', 'admin']
* @param {Object} options.cache - 缓存配置
* @param {number} [options.cache.ttl=300000] - 缓存过期时间(毫秒),默认 5 分钟
*/
constructor({ userId, roles = [], cache = {} }) {
if (!userId || typeof userId !== 'string') {
throw new Error('PermissionManager: userId must be a non-empty string');
}
this.userId = userId;
this.roles = [...new Set(roles)];
507



被折叠的 条评论
为什么被折叠?



