javascript 浅拷贝对象属性描述符时,必须使用 object.assign() 或展开运算符 {...obj} 配合 object.getownpropertydescriptor() 和 object.defineproperty() 手动处理。因为默认的浅拷贝机制只复制属性的值,会丢失原有的 enumerable、writable 等描述符信息。

默认浅拷贝如何丢失属性描述符
当使用展开运算符或 Object.assign 直接拷贝对象时,新对象的所有属性都会变成可枚举(enumerable: true)且可写(writable: true)的普通数据属性,原有的配置如不可枚举或只读会被覆盖。
const original = { a: 1 };
Object.defineProperty(original, 'b', {
value: 2,
enumerable: false,
writable: false
});
// 使用展开运算符进行浅拷贝
const shallowCopy = { ...original };
console.log(shallowCopy); // { a: 1 }
console.log(Object.keys(shallowCopy)); // ['a'] - b 丢失了
console.log(Object.getOwnPropertyDescriptor(shallowCopy, 'a'));
// { value: 1, writable: true, enumerable: true, configurable: true }
运行结果显示,属性 b 因为 enumerable: false 在展开拷贝中被忽略,而属性 a 虽然被拷贝,但其描述符中的 writable 和 enumerable 均变成了默认的 true,失去了对原始属性的精确映射。
如何完整保留属性描述符进行浅拷贝
要保留属性描述符,需要遍历源对象的所有键(包括不可枚举的),获取每个属性的描述符,然后在新对象上重新定义这些属性。
一个基于源码的 OpenAI Agents SDK JavaScript 和 TypeScript 技术文档。涵盖了代理编排、工具、转接、追踪以及实际安装路径。
function deepDescriptorCopy(obj) {
const copy = Object.create(Object.getPrototypeOf(obj));
const descriptors = Object.getOwnPropertyDescriptors(obj);
for (const key in descriptors) {
if (descriptors.hasOwnProperty(key)) {
Object.defineProperty(copy, key, descriptors[key]);
}
}
return copy;
}
const original = { a: 1 };
Object.defineProperty(original, 'b', {
value: 2,
enumerable: false,
writable: false
});
const preservedCopy = deepDescriptorCopy(original);
console.log(preservedCopy); // { a: 1 }
console.log(Object.keys(preservedCopy)); // ['a']
console.log(Object.getOwnPropertyDescriptor(preservedCopy, 'b'));
// { value: 2, writable: false, enumerable: false, configurable: true }
该函数通过 Object.getOwnPropertyDescriptors 获取所有属性的完整描述符,并使用 Object.defineProperty 逐一应用到新对象上,从而完美保留了 enumerable 和 writable 等特性。
基于程序中某个输入、条件或结果的具体问题
在处理包含 getter/setter 的属性描述符时,浅拷贝会将其转换为普通的数据属性,导致访问器行为丢失。
const objWithGetter = {
get name() { return 'test'; }
};
const copyWithGetter = deepDescriptorCopy(objWithGetter);
console.log(typeof copyWithGetter.name); // 'string' - 值被计算并存储
console.log(Object.getOwnPropertyDescriptor(copyWithGetter, 'name'));
// { value: 'test', writable: false, enumerable: true, configurable: true }
// 注意:getter 变成了 value,不再是访问器
这种转换意味着如果原属性是动态计算的 getter,拷贝后的属性将变为静态值,不再响应内部状态的变化。这是在进行深度保留描述符拷贝时必须注意的行为差异。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










