Sub topic 8
Class Instances, Getters and Other Things That Do Not Survive
This chapter assumes you already know how structuredClone makes deep copies and which built-in types it supports (covered in earlier chapters). You should also be comfortable with ES classes, getters and setters, and Object.defineProperty.
structuredClone copies data, not behavior or shape metadata. It walks an object's own enumerable string-keyed properties, reads each value, and writes it onto a brand-new plain object. Anything that is not one of those properties is gone: the prototype chain, accessor functions, property attributes, non-enumerable keys and symbol keys. The copy does not throw an error when this happens. It just comes back with less in it.
How an Ordinary Object Gets Serialized
When the structured clone algorithm meets an ordinary object (anything that is not a recognized built-in such as Date, Map or ArrayBuffer), it follows the same steps every time:
- Create a new empty object whose prototype is
Object.prototype. - List the source's own enumerable, string-keyed properties, in their normal order.
- For each key, read the value with a normal property get. If the property is a getter, the getter runs.
- Clone that value recursively and store it on the new object as a plain data property.
The algorithm never looks at the source's prototype, never copies a property descriptor and never visits symbol keys.
Class Instances Lose Their Class
A class instance is an ordinary object whose prototype is the class's prototype. Methods and getters declared in the class body live on that prototype, not on the instance. Because the algorithm ignores the prototype, the copy has none of them.
class Account {
#balance = 100;
constructor(owner) {
this.owner = owner;
}
get balance() {
return this.#balance;
}
deposit(amount) {
this.#balance += amount;
}
}
const original = new Account('Ada');
const copy = structuredClone(original);
console.log(copy instanceof Account); // false
console.log(copy); // { owner: 'Ada' }
console.log(typeof copy.deposit); // 'undefined'
console.log(copy.balance); // undefinedThe instance loses three separate things here:
- The prototype.
instanceoffails and the methods disappear. - The class getter.
balanceis defined onAccount.prototype, so the algorithm never sees it as an own property. - The private field.
#balanceis not a property at all. Private fields are stored in a separate internal slot that the algorithm cannot reach, so they are silently dropped.
Inherited data works the same way when you build objects with Object.create and no class:
const base = { inherited: 1 };
const child = Object.create(base);
child.own = 2;
console.log(structuredClone(child)); // { own: 2 }Built-in types are the exception
Date, Map, Set, RegExp, typed arrays and the standard error types keep their type. The algorithm recognizes them by their internal slots and rebuilds them on purpose. Your own classes have no such slot, so they fall through to the ordinary-object path.
Subclasses of built-ins are a trap. Modern runtimes rebuild an error as one of the standard constructors, picked by its name. A class ValidationError extends Error comes back as a plain Error, and any extra properties you added (such as field or code) may be missing. Do not rely on custom error subclasses surviving a clone.
Getters Run, Setters Vanish
An accessor property defined directly on the object, for example in an object literal, is an own enumerable property. The algorithm reads it like any other property, which calls the getter once, during cloning. The copy stores the result as a frozen-in-time data value.
let reads = 0;
const source = {
get value() {
reads += 1;
return reads;
}
};
const copy = structuredClone(source);
console.log(reads); // 1 (the getter ran during the clone)
console.log(copy.value); // 1
console.log(copy.value); // 1 (no longer computed)
console.log(Object.getOwnPropertyDescriptor(copy, 'value'));
// { value: 1, writable: true, enumerable: true, configurable: true }This has some consequences that are easy to miss:
- Side effects happen. Logging, lazy initialization, counters or network-triggering getters all fire when you clone.
- Live values become snapshots. A getter such as
get total() { return this.items.length; }returns the right number in the copy only until someone changescopy.items. - A throwing getter aborts the clone. The error the getter threw comes out of
structuredCloneas it is. It is not wrapped in aDataCloneError. - Setter-only properties become
undefined. Reading a property that has a setter but no getter returnsundefined, so the copy gets a key whose value isundefined, and the setter is lost.
try {
structuredClone({ get bad() { throw new Error('nope'); } });
} catch (err) {
console.log(err.name, err.message); // 'Error' 'nope'
}
const setterOnly = structuredClone({ set x(v) {} });
console.log('x' in setterOnly, setterOnly.x); // true undefinedIf your error handling only checks for err.name === 'DataCloneError', a throwing getter will get past it. Catch everything, or check the name and rethrow the rest.
Non-Enumerable Properties and Symbol Keys
The algorithm copies only properties that are both own and enumerable, and only those with string keys. Libraries often use non-enumerable properties and symbol keys for metadata and internal markers, and these get dropped without any warning.
const id = Symbol('id');
const source = { visible: 1, [id]: 2 };
Object.defineProperty(source, 'hidden', { value: 3, enumerable: false });
const copy = structuredClone(source);
console.log(Object.getOwnPropertyNames(copy)); // ['visible']
console.log(Object.getOwnPropertySymbols(copy).length); // 0There is a reason for this. A symbol is unique to its realm and cannot be sent across to a worker or written to IndexedDB, so it cannot be part of a format that is meant for serialization. Non-enumerable properties are skipped for the same reason for...in and Object.keys skip them: they are treated as not part of the object's data.
Property Attributes, Frozen Objects and Null Prototypes
Every property on the copy is a plain data property with writable, enumerable and configurable all set to true. The object's own state is reset as well, so a frozen, sealed or non-extensible source produces an ordinary, fully mutable copy.
const config = Object.freeze({ level: 1 });
const readOnly = {};
Object.defineProperty(readOnly, 'id', { value: 7, writable: false, enumerable: true });
const configCopy = structuredClone(config);
const readOnlyCopy = structuredClone(readOnly);
console.log(Object.isFrozen(configCopy)); // false
configCopy.level = 2;
console.log(configCopy.level); // 2
readOnlyCopy.id = 8;
console.log(readOnlyCopy.id); // 8Objects created with Object.create(null), often used as dictionaries so that keys like __proto__ or toString are safe, come back with Object.prototype as their prototype:
const dict = Object.create(null);
dict.a = 1;
const dictCopy = structuredClone(dict);
console.log(Object.getPrototypeOf(dictCopy) === Object.prototype); // true
console.log('toString' in dictCopy); // trueCode that checks key in dictCopy will now find inherited names such as toString and constructor. Use Object.hasOwn(dictCopy, key), or re-create the dictionary with a null prototype after cloning.
Summary of What Survives
| Feature of the source | What the copy gets |
|---|---|
| Own enumerable string-keyed data property | Copied, value cloned deeply |
| Class prototype and methods | Lost; prototype becomes `Object.prototype` |
| Private fields (`#x`) | Lost |
| Getter on the prototype (class getter) | Lost |
| Own getter (object literal) | Run once; result stored as a data value |
| Own setter | Lost; key exists with value `undefined` if there is no getter |
| Non-enumerable property | Lost |
| Symbol-keyed property | Lost |
| `writable: false`, `configurable: false` | Reset to `true` |
| Frozen, sealed or non-extensible state | Reset; copy is extensible and mutable |
| `Object.create(null)` prototype | Replaced by `Object.prototype` |
| `Date`, `Map`, `Set`, typed arrays, `RegExp` | Type preserved |
Getting Behavior Back After a Clone
structuredClone is a good tool for copying the data inside an instance. You then rebuild the instance yourself. Three patterns cover most cases.
A static factory that takes plain data
Give the class a method that builds an instance from plain data, and pass the cloned data into it. This runs the constructor, so validation and private fields work as normal.
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
get length() {
return Math.hypot(this.x, this.y);
}
static from(plain) {
return new Point(plain.x, plain.y);
}
}
const p = new Point(3, 4);
const copy = Point.from(structuredClone(p));
console.log(copy instanceof Point); // true
console.log(copy.length); // 5
console.log(copy === p); // falseA clone method for classes with private state
Code outside the class cannot read private fields, so the class has to copy itself. Use structuredClone for the nested public data and copy the private fields directly.
class Account {
#balance;
constructor(owner, balance = 0) {
this.owner = owner;
this.#balance = balance;
}
get balance() {
return this.#balance;
}
clone() {
return new Account(structuredClone(this.owner), this.#balance);
}
}
const a = new Account({ name: 'Ada' }, 100);
const b = a.clone();
b.owner.name = 'Grace';
console.log(a.owner.name, b.balance); // 'Ada' 100Re-attaching the prototype
For simple classes that have no private fields and no constructor logic, you can put the prototype back on the copy:
function cloneInstance(instance) {
const data = structuredClone(instance);
return Object.setPrototypeOf(data, Object.getPrototypeOf(instance));
}
class Point {
constructor(x, y) { this.x = x; this.y = y; }
get length() { return Math.hypot(this.x, this.y); }
}
const copy = cloneInstance(new Point(3, 4));
console.log(copy instanceof Point, copy.length); // true 5Copying symbol keys by hand
If you need symbol-keyed data, copy it yourself after cloning. The helper below handles the top level only. Nested objects still lose their symbols.
function cloneWithSymbols(source) {
const copy = structuredClone(source);
for (const sym of Object.getOwnPropertySymbols(source)) {
if (Object.prototype.propertyIsEnumerable.call(source, sym)) {
copy[sym] = structuredClone(source[sym]);
}
}
return copy;
}
const tag = Symbol('tag');
const result = cloneWithSymbols({ a: 1, [tag]: { note: 'kept' } });
console.log(result[tag].note); // 'kept'Common Mistakes
- Cloning state that is stored as class instances, such as in a store or undo history, and then calling methods on the copies. Store plain data, or rebuild instances with a factory.
- Assuming getters stay live. After cloning, a computed property is a stale number.
- Treating
DataCloneErroras the only possible failure. A getter can throw any error. - Relying on
Object.freezeto protect a copy. Freeze the copy again if it must stay immutable. - Using
inon a cloned null-prototype dictionary. UseObject.hasOwn.
Exercise
What does this print, and why? class Temp { constructor(c) { this.c = c; } get f() { return this.c * 9 / 5 + 32; } } const t = structuredClone(new Temp(100)); console.log(t.f, t instanceof Temp);
Show answer
It prints "undefined false". The getter f is defined on Temp.prototype, not on the instance, and structuredClone ignores the prototype. The copy is the plain object { c: 100 } whose prototype is Object.prototype, so it has no f property and is not a Temp.
Exercise
An object is defined as { items: [1, 2], get count() { return this.items.length; } }. After cloning it, you push 3 onto copy.items. What is copy.count, and what is its property descriptor?
Show answer
copy.count is 2. The getter ran once during cloning and its result was stored as a data property, so it no longer tracks items. Its descriptor is { value: 2, writable: true, enumerable: true, configurable: true }.
Exercise
A cache wrapper calls structuredClone(entry) inside try/catch and ignores the error only when err.name === 'DataCloneError'; otherwise it rethrows. One entry has a getter that throws a RangeError. What happens, and is the check correct?
Show answer
structuredClone rethrows the getter's RangeError as it is, so err.name is 'RangeError'. The wrapper rethrows it, and the clone fails with an error from the getter rather than a DataCloneError. The check is correct in that it does not hide unrelated bugs, but code that expects every clone failure to be a DataCloneError would mislabel this case.
Exercise
You need a deep copy of an instance of a class that stores its data in a private field #items (an array of plain objects). Why do both structuredClone(instance) and Object.setPrototypeOf(structuredClone(instance), Proto) fail, and what should you do?
Show answer
structuredClone cannot see private fields, so #items is missing from the copy. Re-attaching the prototype brings the methods back, but any method that reads this.#items throws a TypeError because the copy was never initialized with that field. Add a clone() method inside the class that calls the constructor and passes structuredClone(this.#items), so the new instance gets its own deep copy of the private data.