ES6类不内置深度克隆能力,需在类中封装定制化逻辑:1. 递归+WeakMap处理循环引用;2. toJSON/fromJSON序列化适配;3. 基类或mixin复用克隆逻辑。

ES6 类本身不内置深度克隆能力,但你可以在类中定义自己的 deepClone 方法,或结合序列化逻辑(如 JSON)实现可控的深拷贝。关键不是“类语法自带”,而是“在类内部合理封装克隆逻辑”。下面分三类实用方式说明:
1. 类内封装递归 deepClone 方法(推荐,兼容性强)
适合需要完整保留 Date、RegExp、Map、Set、循环引用等场景。在类中定义静态或实例方法均可:
- 用
WeakMap处理循环引用,避免栈溢出 - 显式判断特殊类型(
Date、RegExp、Array、Map、Set),再分别构造新实例 - 对普通对象使用
Object.create(Object.getPrototypeOf(obj))保持原型链
示例(类中静态方法):
class Person {
constructor(name, birth, hobbies) {
this.name = name;
this.birth = birth; // Date 实例
this.hobbies = hobbies; // 如 new Set(['coding'])
}
static deepClone(obj, hash = new WeakMap()) {
if (obj === null || typeof obj !== 'object') return obj;
if (hash.has(obj)) return hash.get(obj);
let clone;
if (obj instanceof Date) clone = new Date(obj);
else if (obj instanceof RegExp) clone = new RegExp(obj);
else if (obj instanceof Array) clone = obj.map(item => Person.deepClone(item, hash));
else if (obj instanceof Map) {
clone = new Map();
obj.forEach((val, key) => clone.set(Person.deepClone(key, hash), Person.deepClone(val, hash)));
} else if (obj instanceof Set) {
clone = new Set([...obj].map(item => Person.deepClone(item, hash)));
} else {
clone = Object.create(Object.getPrototypeOf(obj));
hash.set(obj, clone);
for (const key of Reflect.ownKeys(obj)) {
clone[key] = Person.deepClone(obj[key], hash);
}
}
return clone;
}
}
// 使用
const p1 = new Person('Alice', new Date('2000-01-01'), new Set(['js']));
const p2 = Person.deepClone(p1); // 完全独立副本
2. 类内提供 toJSON + fromJSON 序列化/反序列化接口
适用于结构较规范、不含函数/Symbol/undefined/循环引用的数据类(如配置类、DTO类)。比纯 JSON 方案更可控:
立即学习“Java免费学习笔记(深入)”;
- 定义
toJSON()方法,只导出可序列化的字段(自动过滤函数、Symbol 等) - 定义静态
fromJSON(json)工厂方法,重建实例并恢复特殊类型(如把时间字符串转回 Date) - 不依赖
JSON.stringify全量转换,规避其固有缺陷
示例:
class User {
constructor(name, createdAt, tags) {
this.name = name;
this.createdAt = createdAt; // Date
this.tags = tags || [];
}
toJSON() {
return {
name: this.name,
createdAt: this.createdAt.toISOString(), // 标准化时间
tags: this.tags
};
}
static fromJSON(json) {
return new User(
json.name,
new Date(json.createdAt),
json.tags
);
}
}
// 使用
const u1 = new User('Bob', new Date(), ['admin']);
const data = u1.toJSON(); // { name: 'Bob', createdAt: '2026-09-05T09:07:00.000Z', ... }
const u2 = User.fromJSON(data); // 新实例,与 u1 完全隔离
3. 类继承时复用克隆逻辑(提升可维护性)
若多个类需深克隆能力,可抽象为基类或 mixin:
- 创建
Clonable基类,含通用clone()实例方法 - 子类调用
super.clone()后,补充自身特有逻辑(如恢复私有字段、重置内部状态) - 避免每个类重复写递归逻辑,也便于统一升级克隆策略
例如:
class Clonable {
clone() {
const json = JSON.stringify(this);
return Object.assign(Object.create(this.constructor.prototype), JSON.parse(json));
}
}
class Config extends Clonable {
constructor(apiUrl, timeout) {
super();
this.apiUrl = apiUrl;
this.timeout = timeout;
this._cache = new Map(); // 不参与克隆
}
clone() {
const copy = super.clone();
copy._cache = new Map(); // 显式重置不可序列化字段
return copy;
}
}
不复杂但容易忽略:深度克隆不是“选一个 API 调用就行”,而要根据类的实际数据结构(是否含特殊对象、是否允许丢失函数、是否需保持原型)来定制。优先在类中封装明确意图的方法,而不是全局泛用 JSON.parse(JSON.stringify())。


















