Sub topic 13
Common Pitfalls and How to Avoid Them
This chapter assumes you already know class accessors, private fields, the #field in obj brand check, and how accessors behave under extends. Each section below describes one mistake, shows what goes wrong, and gives the usual fix.
Recursive Setters
A setter runs every time its property is assigned, and that includes assignments made inside the setter itself. If the setter writes to its own name, it calls itself again and again until the stack overflows.
class Broken {
set name(value) {
this.name = value; // calls the setter again
}
}
// new Broken().name = 'x'; // RangeError: Maximum call stack size exceededThe getter has the same problem when it reads its own name. The fix is to store the value somewhere else, called a backing store. A private field works well for this because nothing outside the class can bypass the accessor.
class Fixed {
#name = '';
get name() { return this.#name; }
set name(value) { this.#name = String(value).trim(); }
}
const f = new Fixed();
f.name = ' Ada ';
console.log(f.name); // 'Ada'Accessors Missing from JSON Output
JSON.stringify only serializes own enumerable data properties. Class accessors live on the prototype and private fields are not properties, so a well-encapsulated class often serializes to {}. To control the output, define a toJSON method that returns the shape you want.
class User {
#email;
constructor(email) { this.#email = email; }
get email() { return this.#email; }
toJSON() {
return { email: this.email };
}
}
console.log(JSON.stringify(new User('[email protected]')));
// '{"email":"[email protected]"}'Spread syntax ({ ...user }) and Object.keys copy and list own enumerable properties only, so they miss accessors and private fields for the same reason. If you need a plain-object copy, build it by hand or call toJSON().
Overriding Only Half of an Accessor
A getter and its setter together make one property. If a subclass defines only get value(), it replaces the whole inherited property with a new one that has no setter. Assignments then fail: they are silently ignored in sloppy mode and throw a TypeError in strict mode, which includes all class bodies. Whenever you override one half, override the other half too and delegate it with super.
class Base {
#value = 1;
get value() { return this.#value; }
set value(v) { this.#value = v; }
}
class Derived extends Base {
get value() { return super.value * 10; }
set value(v) { super.value = v; } // keep the setter
}
const d = new Derived();
d.value = 5;
console.log(d.value); // 50Reading Private Fields from the Wrong Object
Code that reads obj.#x throws a TypeError when obj does not have that field, even inside the class body. When a static helper or a method such as equals(other) accepts arbitrary input, check the input first with a brand check.
class Point {
#x = 0;
static getX(p) {
return #x in p ? p.#x : undefined;
}
}
console.log(Point.getX(new Point())); // 0
console.log(Point.getX({})); // undefinedProxies and Private Fields
A Proxy does not forward private field access. When you read a getter through a proxy, the getter runs with this set to the proxy. The proxy has no #v, so the getter throws. The fix is a get trap that uses the target as the receiver, plus binding methods to the target so they behave the same way.
class Box {
#v = 42;
get v() { return this.#v; }
double() { return this.#v * 2; }
}
const target = new Box();
const safe = new Proxy(target, {
get(t, prop) {
const value = Reflect.get(t, prop, t); // getter runs with this === t
return typeof value === 'function' ? value.bind(t) : value;
}
});
console.log(safe.v); // 42
console.log(safe.double()); // 84The trade-off is that this inside your methods is now the raw target, so any other traps on the proxy will not see those internal accesses.
Summary Table
| Pitfall | Symptom | Fix |
|---|---|---|
| Recursive setter | RangeError | Store the value in a private backing field |
| Serialization | `{}` from `JSON.stringify` | Define `toJSON` |
| Half-overridden accessor | Assignments ignored or TypeError | Override both halves and delegate with `super` |
| Foreign object | TypeError on `obj.#x` | Check with `#x in obj` first |
| Proxy | TypeError inside getter | Use `Reflect.get(t, prop, t)` and bind methods |
Exercise
A class has get total() { return this.total ?? 0; }. What happens when you read instance.total, and how do you fix it?
Show answer
The getter reads this.total, which calls the getter again. The recursion continues until a RangeError is thrown. The fix is to keep the value in a separate backing store, such as a private field #total, and read this.#total ?? 0 instead.
Exercise
Why does JSON.stringify(new Box()) produce '{}' for the Box class above, and what is a one-method fix?
Show answer
v is an accessor on the prototype and #v is a private field. JSON.stringify only includes own enumerable data properties, so it skips both. Adding toJSON() { return { v: this.v }; } makes the output '{"v":42}'.