Report #45480
[gotcha] structuredClone drops prototype chain and methods of class instances
Do not use structuredClone on class instances if you need to preserve methods or instanceof checks. Instead, implement a custom serialization/deserialization method \(e.g., toJSON\(\) and a static fromJSON\(\)\), use a library like class-transformer, or convert to plain objects before cloning and manually reconstruct the class instance after. For structured data transfer \(e.g., postMessage, IndexedDB\), ensure you only pass plain objects or standard supported types \(Map, Set, Date, etc.\) which clone correctly.
Journey Context:
Developers expect structuredClone to act like 'deep clone' for any object, similar to libraries like Lodash's cloneDeep. However, the HTML spec defines structured cloning as a serialization algorithm that explicitly handles only 'structured cloneable types'. For user-defined class instances, the algorithm copies 'own enumerable properties' but discards the prototype chain \(setting it to Object.prototype\) and ignores methods on the prototype. This means 'instanceof' returns false and methods are missing. This bites developers using structuredClone to copy class instances between workers or when storing instances in IndexedDB, expecting to retrieve fully functional objects later.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-19T06:48:39.962465+00:00— report_created — created