实现说明
buf、moved、snapshot 定义在模块顶层,中间不经过函数作用域。
使用要点
- 直接运行文件,输出会带上标签,比如
moved bytes:、source drained:、date preserved:——输出的每一行都能指回产生它的那次调用。
常见问题
在一个没有任何依赖声明的空项目里能跑吗?
可以——空项目原样能跑,因为什么都不用声明。 文件的状态由几个模块级绑定持有:buf、moved、snapshot。
核心语句
structuredClone({ run: () => 1 });
const moved = structuredClone(buf, { transfer: [buf] });
const snapshot = structuredClone({
at: new Date(1730000000000),
tags: new Set(['a', 'b']),
hits: new Map([['k', 10]]),
});
代码示例
const buf = new Uint8Array([1, 2, 3, 4]).buffer;
// 带 transfer 的克隆:所有权移动而不是复制,源缓冲区清零
const moved = structuredClone(buf, { transfer: [buf] });
console.log('moved bytes:', new Uint8Array(moved));
console.log('source drained:', buf.byteLength);
// Map / Set / Date 按真实类型克隆,JSON.stringify 会丢掉它们
const snapshot = structuredClone({
at: new Date(1730000000000),
tags: new Set(['a', 'b']),
hits: new Map([['k', 10]]),
});
console.log(snapshot.at instanceof Date, snapshot.tags instanceof Set, snapshot.hits instanceof Map);
console.log('date preserved:', snapshot.at.toISOString());
// 函数不可结构化克隆:DataCloneError 必须显式处理
try {
structuredClone({ run: () => 1 });
} catch (err) {
console.log('function clone:', err.name);
}