如何使用 structuredClone 进行深拷贝?它有什么局限性?
请说明 structuredClone 的用法、支持的类型和局限性。
回答
屠龙少年
structuredClone:HTML 标准提供的深拷贝函数,全局可用(浏览器和 Node 17+)。
用法:
const cloned = structuredClone(original);
// 第二个参数可选:transfer(转移可转移对象的所有权)
const transferred = structuredClone(buffer, { transfer: [buffer] });
支持的类型:
- 基本类型、Array、对象字面量
- Date、RegExp、Map、Set、Blob、File、ImageData
- ArrayBuffer、TypedArray(需 transfer)
- Error 对象、DOMException
- 循环引用(自动处理,不报错)
不支持的类型(会抛 DataCloneError):
- Function(报错)
- DOM 节点(Element/Document,报错)
- Symbol
- WeakMap/WeakSet
- Promise、Proxy
- 自定义类的实例(不会运行构造函数,只拷贝可枚举属性)
与 JSON.parse(JSON.stringify()) 对比:
structuredClone({ a: undefined, b: new Date(), c: /regex/ });
// ✅ Date、RegExp 保留,循环引用正常
// undefined 被转为 null(而非忽略)
JSON.parse(JSON.stringify({ a: undefined, b: /regex/ }));
// ❌ undefined 消失,RegExp 变 {},Date 变字符串
适用场景:大多数业务需求的深拷贝首选。