深浅拷贝与设计模式
约 320 字大约 1 分钟
布欧-Lewyon
2026-05-16
首页 › JavaScript › 进阶实践 › 深浅拷贝与设计模式
深浅拷贝
// 浅拷贝:只拷贝第一层
const obj = { a: 1, b: { c: 2 } };
const shallow1 = { ...obj };
const shallow2 = Object.assign({}, obj);
shallow1.b.c = 99; // ❌ 原对象也被修改
// 深拷贝
const deep1 = JSON.parse(JSON.stringify(obj));
// 缺点:不支持函数、undefined、Symbol、循环引用
const deep2 = structuredClone(obj); // ✅ 推荐(现代浏览器支持)
// 支持循环引用、Date、Map、Set 等
// 递归深拷贝(简易版)
function deepClone(value, cache = new WeakMap()) {
if (value === null || typeof value !== 'object') return value;
if (cache.has(value)) return cache.get(value); // 循环引用
const cloned = Array.isArray(value) ? [] : {};
cache.set(value, cloned);
for (let key of Reflect.ownKeys(value)) {
cloned[key] = deepClone(value[key], cache);
}
return cloned;
}设计模式
// 单例模式
const Singleton = (function() {
let instance;
return {
getInstance() {
if (!instance) instance = { /* 初始化 */ };
return instance;
}
};
})();
// 观察者模式
class EventBus {
constructor() {
this.events = {};
}
on(event, handler) {
(this.events[event] ||= []).push(handler);
}
emit(event, data) {
(this.events[event] || []).forEach(fn => fn(data));
}
off(event, handler) {
this.events[event] = this.events[event]?.filter(fn => fn !== handler);
}
}小结
| 拷贝 | 方式 | 限制 |
|---|---|---|
| 浅拷贝 | ... / Object.assign | 嵌套对象共享引用 |
| JSON 深拷贝 | JSON.parse/stringify | 不支持函数/undefined/循环引用 |
| structuredClone | 内置深拷贝 | 现代浏览器支持 |
上一节:防抖与节流 下一节:Web API 与调试
