structuredClone(value) là hàm built-in deep-clone, dùng thuật toán structured clone của nền tảng (cùng cơ chế postMessage của Web Worker).
Hơn JSON.parse(JSON.stringify(x)) ở chỗ:
- Giữ được Date, RegExp, Map, Set, ArrayBuffer, TypedArray, Blob, File — JSON làm hỏng (Date thành string, Map thành {}).
- Xử lý đúng circular reference — JSON ném lỗi Converting circular structure.
- Giữ undefined trong mảng, không cần serialize qua string nên nhanh hơn cho object lớn.
const src = { d: new Date(), m: new Map([['k', 1]]), nested: {} };
src.self = src; // circular
const copy = structuredClone(src);
copy.d instanceof Date; // true
copy.self === copy; // trueKhông clone được (ném DataCloneError): function, Symbol, DOM node, và prototype tùy biến — kết quả luôn là plain object, mất class instance (copy instanceof MyClass → false). Getter/setter và property non-enumerable cũng bị mất.
Lưu ý: đồng bộ, có sẵn ở browser hiện đại và Node 17+.
structuredClone(value) is a built-in deep-clone using the platform's structured clone algorithm (the same mechanism behind Web Worker postMessage).
Better than JSON.parse(JSON.stringify(x)) because it:
- Preserves Date, RegExp, Map, Set, ArrayBuffer, TypedArray, Blob, File — JSON mangles these (Date → string, Map → {}).
- Handles circular references — JSON throws Converting circular structure.
- Keeps undefined in arrays and skips string serialization, faster for big objects.
const src = { d: new Date(), m: new Map([['k', 1]]), nested: {} };
src.self = src; // circular
const copy = structuredClone(src);
copy.d instanceof Date; // true
copy.self === copy; // trueCannot clone (throws DataCloneError): function, Symbol, DOM nodes, and custom prototypes — the result is always a plain object, losing class instances (copy instanceof MyClass → false). Getters/setters and non-enumerable props are also lost.
Note: synchronous; available in modern browsers and Node 17+.