第 15 周总结:Class 与模块化 — 工程化地基落成
蜗牛往上爬 · 前端工业可视化学习笔记 第 15 周总结
本周把原型继承升级为现代 Class(getter/私有字段/静态/继承/多态),用 ES Module 把单文件项目拆成分层工程。设备管理系统完成了从"一个 script"到"类/数据/渲染/入口分层"的蜕变——这正是阶段2 框架工程的前身。
目录
一、本周学了什么
知识图谱
Class 与模块化
├── Class
│ ├── class / constructor(本质是函数语法糖)
│ ├── getter / setter(属性访问器 + 校验)
│ ├── #field 私有字段(类外不可访问)
│ ├── static 静态成员(工具/计数)
│ ├── extends 继承 + super(先 super 再 this)
│ ├── 方法重写 + super.method()
│ └── 多态:同一方法不同实现
│
└── ES Module
├── 命名导出(多个,import {} 同名)
├── 默认导出(一个,import X 随意名)
├── as 重命名 / * as 命名空间 / import() 动态
├── 模块规则:私有作用域、只读视图、单例、严格模式
├── <script type="module"> + Live Server
└── 分层架构:入口→渲染→业务→模型→工具
二、核心知识速记
三条铁律
子类 constructor 必须先
super(...)再用this默认导出一个文件只有一个,导入时不用
{}模块内变量天然私有——数据保护首选模块级变量
高频写法
// 类 + getter 派生值
class Device {
constructor(id, temp) { this.id = id; this.temp = temp; }
get level() { return this.temp >= 80 ? "危险" : "正常"; }
}
// 继承 + 重写 + super
class CNC extends Device {
constructor(id, temp, speed) {
super(id, temp);
this.speed = speed;
}
toJSON() { return { ...super.toJSON(), speed: this.speed }; }
}
// 模块私有数据(store 模式)
let devices = []; // 外部改不到
export const addDevice = d => devices.push(d);
// 混合导入
import Device, { formatTemp } from "./device.js";
命名导出 vs 默认导出
在工业可视化里的应用场景
三、本周踩过的坑
坑点 1:子类用了 this 忘了先 super
// ❌ ReferenceError: Must call super constructor
class CNC extends Device {
constructor(id, name, temp) {
this.id = id; // ❌ super 之前不能用 this
super(id, name, temp);
}
}
// ✅ 先 super
class CNC extends Device {
constructor(id, name, temp) {
super(id, name, temp);
this.extra = true; // super 之后再写子类属性
}
}
坑点 2:默认导出的导入加了 {}
// Device.js 是 export default class Device {...}
// ❌ 拿到的是 undefined
import { Device } from "./Device.js";
// ✅ 默认导出不加 {}
import Device from "./Device.js";
坑点 3:导入命名导出时改名
// utils.js: export function formatTemp() {...}
// ❌ 名字不一致 → undefined
import { formatTemperature } from "./utils.js";
// ✅ 同名,或用 as 重命名
import { formatTemp } from "./utils.js";
import { formatTemp as fmt } from "./utils.js";
坑点 4:忘了 type=“module”
<!-- ❌ 普通 script:import 语法报错 -->
<script src="js/app.js"></script>
<!-- ✅ 声明 module -->
<script type="module" src="js/app.js"></script>
坑点 5:file:// 协议直接打开页面
❌ 双击打开 index.html → 控制台报 CORS 错误(模块受同源策略限制)
✅ 用 VS Code 的 Live Server 插件,或 npx serve 起本地服务
坑点 6:getter 里当方法调用
// ❌ getter 不是方法,不能加括号调用
console.log(device.level()); // TypeError: level is not a function
// ✅ 像属性一样访问
console.log(device.level); // "危险"
四、自测清单
[ ] class 和构造函数的关系?(语法糖,typeof 是 function)
[ ] class 有变量提升吗?能不 new 直接调用吗?
[ ] getter/setter 怎么写?怎么访问?
[ ] # 私有字段外部能访问吗?
[ ] static 成员怎么调用?适合什么场景?
[ ] extends 继承了什么?super 的两个用法?
[ ] 子类 constructor 的 super 必须在什么之前?
[ ] 方法重写后怎么调父类版本?
[ ] 什么是多态?举一个例子?
[ ] 命名导出和默认导出的区别?
[ ] 导入默认导出时加不加 {}?
[ ] import * as 和 import() 分别是什么?
[ ] 模块的四条规则?
[ ] 浏览器怎么启用 ESM?为什么要用 Live Server?
[ ] 模块化项目的分层架构是哪几层?
[ ] store 模块怎么保护数据不被外部直接修改?
五、下周预告
第 16 周:进阶特性与综合实战(阶段1 收官)⭐
下周把 10 周所学全部融进一个收官项目,并输出阶段1 毕业总结——之后正式进入阶段2:智慧工厂大屏项目!
🚀 第 15 周完成!工程化地基已打好。下周阶段1 收官之战——综合实战见真章!