实现说明
structuredClone 会丢掉类原型可以归结为类 Invoice。
各个操作都建立在顶层绑定之上:original、cloned、revived、withDate。
使用要点
- 跑完文件,输出里会留下标记——
original total: $、cloned data: $、cloned.total is function: $。
常见问题
有需要管理的依赖吗?
没有。无需声明或安装任何依赖。 跨调用保留的状态放在这些顶层绑定里:original、cloned、revived。
核心语句
const withDate = structuredClone({ due: new Date("2026-03-01T00:00:00Z"), tags: ["net-30"] });
const cloned = structuredClone(original);
代码示例
class Invoice {
number: string;
paidCents: number;
constructor(number: string, paidCents = 0) {
this.number = number;
this.paidCents = paidCents;
}
total(): number {
return this.paidCents;
}
}
const original = new Invoice("INV-1", 4900);
console.log(`original total: ${original.total()}`);
// structuredClone 按结构复制:类型参数声称 T,原型与方法不会跟着走
const cloned = structuredClone(original);
console.log(`cloned data: ${cloned.number} ${cloned.paidCents}`);
console.log(`cloned.total is function: ${typeof cloned.total}`);
const revived = Object.assign(Object.create(Invoice.prototype), cloned);
console.log(`revived total: ${revived.total()}`);
// 普通数据(数组/日期/Map)克隆是安全的
const withDate = structuredClone({ due: new Date("2026-03-01T00:00:00Z"), tags: ["net-30"] });
console.log(`due: ${withDate.due.toISOString()}, tags: ${withDate.tags.join(",")}`);