← 中文资源

简体中文版本

structuredClone 会丢掉类原型

structuredClone 按结构复制数据:泛型返回值仍声称 T,但类的方法与原型不会跟随,需用 Object.create 挂回原型;Date、Map 等普通数据克隆是安全的。

阅读英文原文

实现说明

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(",")}`);