StructuredClone Moves With Transfer

structuredClone deep-copies Maps, Sets, and Dates that JSON.stringify drops, and its transfer option moves ArrayBuffer ownership instead of copying bytes.

JavascriptData Integrity

Code

javascriptsnippet
22 lines
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);
}

Output

Captured from a sandboxed run of this snippet in the build pipeline.

moved bytes: Uint8Array(4) [ 1, 2, 3, 4 ]
source drained: 0
true true true
date preserved: 2024-10-27T03:33:20.000Z
function clone: DataCloneError

What the code does

Module-level bindings hold the data — buf, moved, snapshot — with no function scope in between.

Applying it

The demo output is labeled (moved bytes:, source drained:, date preserved:), so every printed line maps back to its originating operation.

Statements that matter

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]]),
});

Interactive Tools for This Topic

FAQ

Does this work in a bare project with no dependencies file?
Yes — a bare project runs it as-is, since nothing needs declaring. Its state lives in module-level bindings: `buf`, `moved`, `snapshot`.