深拷贝带 getter 的对象必须用 object.getownpropertydescriptors + object.defineproperties 重建访问器属性;对 getter 直接赋值 desc.get 即可,this 自动指向新对象,仅当依赖原对象 identity 时才需 bind;value 属性需递归深拷贝并用 weakmap 处理循环引用。

JavaScript 中深拷贝带有 getter 的属性,不能靠 JSON.parse(JSON.stringify()) 或简单递归遍历对象实现,因为 getter 是访问器属性,不存储实际值,而是运行时动态计算。要保留 getter(即新对象上也要有同名 getter),必须显式读取原始描述符并重新定义。
用 Object.getOwnPropertyDescriptors + Object.defineProperties
这是最直接、可控的方式:获取源对象所有自有属性的完整描述符(含 get、set、enumerable、configurable 等),再在新对象上逐个定义。
- 对每个属性,检查
descriptor.get是否存在;若存在,就用该函数作为新 getter - 普通数据属性(
value)需递归深拷贝(如遇到对象/数组) - 注意处理循环引用,否则会爆栈(可加 WeakMap 缓存已拷贝对象)
示例:
function deepCloneWithGetters(obj, seen = new WeakMap()) {
if (obj === null || typeof obj !== 'object') return obj;
<p>if (seen.has(obj)) return seen.get(obj);</p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill3430" title="Alibabacloud Sdk Client Initialization For Java"><img
src="https://img.php.cn/upload/skill/000/000/081/178955835420587.jpg" alt="Alibabacloud Sdk Client Initialization For Java" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/skill3430" title="Alibabacloud Sdk Client Initialization For Java" class="overflowclass">Alibabacloud Sdk Client Initialization For Java</a>
<p class="overflowclass">在 Java 中初始化和管理阿里云 SDK客户端。包括单例模式、线程安全、endpoint 与 region 配置、VPC 终端节点、同步与异步等。</p>
</div>
<a rel="nofollow" href="/xiazai/skill3430" title="Alibabacloud Sdk Client Initialization For Java" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div><p>const cloned = Array.isArray(obj) ? [] : {};
seen.set(obj, cloned);</p><p>const descriptors = Object.getOwnPropertyDescriptors(obj);
for (const key in descriptors) {
const desc = descriptors[key];
if ('get' in desc && typeof desc.get === 'function') {
Object.defineProperty(cloned, key, {
get: desc.get.bind(obj), // 绑定原对象上下文,确保 this 正确
enumerable: desc.enumerable,
configurable: desc.configurable
});
} else if ('value' in desc) {
cloned[key] = deepCloneWithGetters(desc.value, seen);
}
}</p><p>return cloned;
}</p><p>// 使用示例
const source = {
a: 1,
get b() { return this.a * 2; }
};
const copy = deepCloneWithGetters(source);
console.log(copy.b); // 2 —— getter 正常工作</p>注意 getter 中的 this 指向
getter 函数内的 this 默认指向调用它的对象。若直接赋值 get: desc.get 而不绑定,复制后调用时 this 会指向新对象 —— 这通常是期望行为。但若原 getter 依赖原对象私有状态(比如闭包变量或 Symbol 属性),仅靠描述符无法迁移,此时需额外逻辑或重构设计。
- 多数情况下
desc.get.bind(obj)不必要,直接get: desc.get即可(让 this 自动指向新对象) - 只有当 getter 显式依赖原对象 identity(如用 WeakMap 缓存)时,才需 bind 原对象并做特殊处理
避开 getter,只拷贝运行时值?
如果目标只是“拿到 getter 当前计算出的值”,而非保留 getter 行为,那更简单:遍历属性名,用 Reflect.get(obj, key) 读值,再深拷贝该值。
- 适合只关心快照结果的场景(如序列化配置)
- 但丢失响应性 —— 新对象属性不再随原对象变化而更新
- 无法还原 setter、不可枚举属性、不可配置状态
不复杂但容易忽略:深拷贝不是单纯复制数据,而是重建行为契约。带 getter 的对象,拷贝的本质是复刻访问逻辑,而非搬运值。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










