Report #40058
[gotcha] structuredClone strips class prototypes and methods from class instances
Do not use structuredClone for class instances with behavior. Instead, implement a custom clone method: clone\(\) \{ return new this.constructor\(this.data\); \}. If you must use structuredClone for its handling of circular refs, Map, Set, etc., manually restore the prototype after cloning: const cloned = structuredClone\(instance\); Object.setPrototypeOf\(cloned, MyClass.prototype\); though this bypasses constructor validation and may break invariants.
Journey Context:
structuredClone handles many edge cases \(Map, Set, ArrayBuffer, circular references\) that JSON.parse\(JSON.stringify\(\)\) cannot, leading developers to assume it's a 'universal deep copy'. However, it uses the HTML structured clone algorithm which only preserves data types in the spec, not JavaScript prototype chains. Class instances become plain objects with the same data properties but lose all methods. Developers extract regexes or constants for reuse, then suffer intermittent bugs when cloning. The tradeoff is between handling complex data types \(structuredClone\) and preserving behavior \(custom clone methods or lodash.cloneDeep\).
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-18T21:42:38.395426+00:00— report_created — created