JavaScript structuredClone 实战:循环引用、类型边界与 ArrayBuffer 转移
复制一份状态,最容易漏测的并非字段值,而是引用关系。两个字段原本指向同一对象,复制后还该不该相等?对象指回自身会不会报错?本文用七组可运行断言检验结构化克隆的边界,再解释什么时候应该复制字节,什么时候可以转移所有权。

先确定运行环境与预期
实测环境为已安装的 Node.js v24.19.0,没有安装依赖或升级运行时。Node 官方文档将 structuredClone 列为全局方法。以下只使用内存中临时构造的数据,不访问文件、网络或业务缓存;代码断言的是行为,不是性能排名。
复制的是对象图,不是逐字段拆散
第一组测试让左右字段共用一个子对象,同时让根对象指向自己。复制后的根与原根不同,左右字段却仍指向同一个新子对象,自引用也回到新根。修改副本左侧会影响副本右侧,但不会修改原子对象。这种“内部关系保留、与原图分离”的区别,比只检查内容相等更重要。MDN 方法说明也给出了循环引用语义。
第二组把同一个对象同时放进普通字段、Map 键和值、Set 成员中。复制后应使用副本里的键对象查询新集合,原键查不到属于正常结果。日期仍是 Date,时间值相同但身份不同。这里验证的是受支持内建类型的数据语义,不能据此推断任意库对象都能完整恢复。
失败、降级与取值副作用要分开
函数和 WeakMap 放在可枚举字段中,都会使整个调用抛出 DataCloneError,而非自动删除该字段后成功。测试只核对异常名称,不依赖可能随版本变化的报错文本。HTML 标准明确区分可调用对象、受支持内建类型及不能序列化的内部状态。
自定义类实例可能成功复制,但结果不再是原类实例。原型方法、私有字段与不可枚举属性不会成为可用的类行为。示例还检查了只读属性变成可写数据属性,以及访问器在读取时执行一次,结果保存为普通值。不要把“没有抛错”当成“完整克隆”;需要恢复类不变量时,应明确导出数据,再由受控构造流程恢复。相关限制见 MDN 算法说明。
普通复制与转移的所有权差别
普通 ArrayBuffer 克隆会复制字节,原缓冲区保留。新视图与新缓冲区仍相互对应,修改新视图不影响旧数据。转移则在调用成功后让原缓冲区脱离底层资源,原视图也受影响:本例字节长度归零,重新创建视图或通过原数据视图读取会抛错。不能笼统声称脱离后的所有属性访问都会抛错。
转移列表填写底层缓冲区,而非类型化数组视图;该资源还应能从输入值访问到,否则列表本身不会把它附加到返回结果。转移后得到的是新的对象包装,不是原对象变了变量名。它可以避免复制该缓冲区的字节,但对象图仍需处理,不代表整个调用零成本,也不会自动启动线程。详见 MDN 可转移对象说明。
完整断言脚本
将下面完整内容保存为 fullcode.mjs。每组数据均重新创建,尤其不要拿还被其他模块使用的缓冲区试验转移。测试输出按固定顺序列出七项结果,任意断言失败都会让进程报错退出。
import assert from 'node:assert/strict';
let passed = 0;
function check(name, fn) {
fn();
passed += 1;
console.log(`ok ${passed} - ${name}`);
}
check('shared references and cycles', () => {
const shared = { count: 1 };
const source = { left: shared, right: shared };
source.self = source;
const copy = structuredClone(source);
assert.notEqual(copy, source);
assert.equal(copy.left, copy.right);
assert.equal(copy.self, copy);
assert.notEqual(copy.left, shared);
copy.left.count = 9;
assert.equal(copy.right.count, 9);
assert.equal(shared.count, 1);
});
check('Date, Map and Set keep data relationships', () => {
const key = { id: 7 };
const source = {
key,
date: new Date('2026-01-02T03:04:05.000Z'),
map: new Map([[key, { owner: key }]]),
set: new Set([key]),
};
const copy = structuredClone(source);
assert.ok(copy.date instanceof Date);
assert.ok(copy.map instanceof Map);
assert.ok(copy.set instanceof Set);
assert.equal(copy.date.getTime(), source.date.getTime());
assert.equal(copy.map.get(copy.key).owner, copy.key);
assert.equal(copy.map.has(key), false);
assert.ok(copy.set.has(copy.key));
assert.equal(copy.set.has(key), false);
copy.date.setUTCFullYear(2030);
assert.equal(source.date.getUTCFullYear(), 2026);
});
check('functions and WeakMap are rejected', () => {
for (const value of [() => 1, new WeakMap()]) {
assert.throws(() => structuredClone({ nested: value }), {
name: 'DataCloneError',
});
}
});
check('class prototypes and descriptors are not preserved', () => {
class Ticket {
#secret = 'local only';
constructor() { this.title = 'demo'; }
label() { return `${this.title}:${this.#secret}`; }
}
const source = new Ticket();
let reads = 0;
Object.defineProperties(source, {
fixed: { value: 3, enumerable: true, writable: false },
hidden: { value: 'not copied', enumerable: false },
computed: { enumerable: true, get() { reads += 1; return 6; } },
});
const copy = structuredClone(source);
assert.equal(Object.getPrototypeOf(copy), Object.prototype);
assert.equal(copy instanceof Ticket, false);
assert.equal(copy.label, undefined);
assert.throws(() => Ticket.prototype.label.call(copy), TypeError);
assert.equal(Object.hasOwn(copy, 'hidden'), false);
assert.equal(reads, 1);
assert.deepEqual(Object.getOwnPropertyDescriptor(copy, 'computed'), {
value: 6, writable: true, enumerable: true, configurable: true,
});
copy.fixed = 8;
assert.equal(copy.fixed, 8);
assert.equal(source.fixed, 3);
});
check('ordinary ArrayBuffer clone copies bytes', () => {
const buffer = new ArrayBuffer(4);
const bytes = new Uint8Array(buffer);
bytes.set([10, 20, 30, 40]);
const copy = structuredClone({ buffer, bytes });
assert.notEqual(copy.buffer, buffer);
assert.equal(copy.bytes.buffer, copy.buffer);
assert.deepEqual([...copy.bytes], [10, 20, 30, 40]);
copy.bytes[0] = 99;
assert.equal(bytes[0], 10);
assert.equal(buffer.byteLength, 4);
});
check('transfer detaches the original ArrayBuffer and its views', () => {
const buffer = new ArrayBuffer(4);
const bytes = new Uint8Array(buffer);
const view = new DataView(buffer);
bytes.set([1, 2, 3, 4]);
const moved = structuredClone({ buffer, bytes }, { transfer: [buffer] });
assert.notEqual(moved.buffer, buffer);
assert.equal(moved.bytes.buffer, moved.buffer);
assert.deepEqual([...moved.bytes], [1, 2, 3, 4]);
assert.equal(buffer.byteLength, 0);
assert.equal(bytes.byteLength, 0);
assert.throws(() => new Uint8Array(buffer), TypeError);
assert.throws(() => view.getUint8(0), TypeError);
});
check('JSON round-trip has different semantics', () => {
const shared = { count: 1 };
const source = {
left: shared, right: shared,
date: new Date('2026-01-02T03:04:05.000Z'),
map: new Map([['a', 1]]), set: new Set([1]),
};
const copy = JSON.parse(JSON.stringify(source));
assert.notEqual(copy.left, copy.right);
assert.equal(typeof copy.date, 'string');
assert.deepEqual(copy.map, {});
assert.deepEqual(copy.set, {});
source.self = source;
assert.throws(() => JSON.stringify(source), TypeError);
});
console.log(`PASS: ${passed} deterministic checks`);在脚本所在目录运行:
node --version node fullcode.mjs
如何解释测试结果
本机七组断言全部通过,末行输出“PASS: 7 deterministic checks”。最后一组特意走了一次 JSON 往返:日期变字符串,集合内容不按集合语义保存,共用引用被拆开,循环引用报错。因此两条路径不能仅凭“都返回新对象”互换。跨语言传输仍应使用明确定义的数据格式,而不是把内存克隆当作通用文件格式。
落地时先列出允许的数据类型,再选复制还是转移,并保留这些断言作为回归测试。结构化克隆也不是安全边界:访问器可能执行,内容不会自动校验、脱敏或冻结。本文普通缓冲区的独立副本结论不适用于共享内存;遇到 SharedArrayBuffer 或宿主扩展对象,应另查规则并单独测试,避免把局部成功扩大成所有对象都安全。
如果应用状态混有回调与业务字段,先定义只含数据的传输对象,不要在失败后悄悄改用另一套复制方式。调用方应知道哪些字段必须保留、哪些可以省略,以及转移后谁负责继续持有数据。把这些约定写进测试,比给函数起一个“万能深拷贝”的名字更可靠。
资料核验于北京时间 2026 年 10 月 21 日。正文结论结合上述官方资料与本机断言;未对其他运行时版本进行覆盖测试。

