Sub topic 12
Accessors and Private State Across Subclasses
This chapter assumes you know ES2015 class and extends syntax, how super calls work, how the prototype chain resolves property lookups, and the basics of strict mode. It also builds on the earlier chapters on class accessors and private # fields.
Accessors and private fields behave differently under inheritance. Accessors are ordinary properties on prototypes, so subclasses inherit and override them through the prototype chain. Private fields belong to one class body. A subclass instance carries them, but code in the subclass cannot see them. Most inheritance bugs in this area come from mixing up those two models.
How Inherited Accessors Are Looked Up
A class accessor lives on the class's prototype object as a single accessor property. Its descriptor holds both get and set. When you read or write obj.value, JavaScript walks the prototype chain and stops at the first object that has its own value property. It then uses that property's descriptor, even if the descriptor is incomplete.
Overriding only the getter hides the setter
This is the most common accessor inheritance bug. Defining get value() in a subclass creates a new accessor property on Derived.prototype, and its set is undefined. The subclass does not merge with the parent's pair. Writes stop at the subclass property and fail.
'use strict';
class Base {
#value = 1;
get value() { return this.#value; }
set value(v) { this.#value = v; }
}
class GetterOnly extends Base {
get value() { return super.value * 10; }
}
const g = new GetterOnly();
console.log(g.value); // 10
try {
g.value = 5; // GetterOnly.prototype.value has no setter
} catch (err) {
console.log(err instanceof TypeError); // true
}
console.log(g.value); // still 10In sloppy-mode code the assignment fails without an error, which is worse. Class bodies are always strict, but the code doing the assignment might not be.
The fix is to override both halves and delegate through super:
class Base {
#value = 1;
get value() { return this.#value; }
set value(v) { this.#value = v; }
}
class Scaled extends Base {
get value() { return super.value * 10; }
set value(v) { super.value = v / 10; }
}
const s = new Scaled();
s.value = 50;
console.log(s.value); // 50 (Base stores 5, Scaled reports 5 * 10)super.value reads the property from Base.prototype but runs the getter with this set to the current instance. super.value = x does the same with the setter. That is why the parent's setter can still write this.#value: the receiver is the Scaled instance, and that instance does carry Base's private field.
Private Fields Belong to the Declaring Class
A private name such as #name is lexically scoped to the class body that declares it. When a subclass instance is constructed, the Animal constructor installs Animal's private fields on the new object. The object really has #name. Only code written inside Animal's body can reach it, though.
class Animal {
#name;
constructor(name) { this.#name = name; }
get name() { return this.#name; }
}
class Dog extends Animal {
#tricks = [];
learn(trick) { this.#tricks.push(trick); }
describe() {
// return this.#name; // SyntaxError: #name is not declared in Dog
return `${this.name} knows ${this.#tricks.join(', ')}`;
}
}
const rex = new Dog('Rex');
rex.learn('sit');
rex.learn('roll over');
console.log(rex.describe()); // Rex knows sit, roll overDog gets to the name through the public name getter that Animal defines. That getter runs Animal's code, so this.#name resolves there. This is the normal pattern: the parent exposes accessors, and subclasses use them.
JavaScript has no protected modifier. If you want subclasses to get more access than outside code, your options are all conventions:
| Approach | Subclass access | Outside access | Notes |
|---|---|---|---|
| Public accessor on parent | Yes | Yes | Simplest; validation stays in the parent |
| Underscore property `_name` | Yes | Yes, by convention "don't" | No enforcement |
| Symbol-keyed property | Yes, if the symbol is shared | Via `Object.getOwnPropertySymbols` | Module-level privacy only |
| `#name` private field | No | No | Strict privacy, no subclass access |
Same private name, two separate fields
Because private names are scoped per class, a subclass can declare a field with the same spelling. That creates a second, unrelated slot on the same object.
class A {
#id = 'A';
getA() { return this.#id; }
}
class B extends A {
#id = 'B';
getB() { return this.#id; }
}
const b = new B();
console.log(b.getA(), b.getB()); // A BBoth fields live on b. Methods from A see A's #id, and methods from B see B's. Public properties work the opposite way: two classes using the same name share one property. If you reuse a private name expecting to override the parent's field, the parent will keep reading its own copy.
Construction Order and Private Fields
The order of field initialization matters once constructors call methods that subclasses override.
The parent's fields are installed before the parent constructor body runs. A derived class's fields are installed right after super() returns. During the parent constructor, the subclass's private fields do not exist on the object yet.
class Widget {
constructor() {
this.render(); // calls the subclass override
}
render() { console.log('base render'); }
}
class Label extends Widget {
#text = 'hello';
render() { console.log(this.#text); }
}
try {
new Label();
} catch (err) {
console.log(err instanceof TypeError); // true
// "Cannot read private member #text from an object whose class did not declare it"
}The same failure happens if a parent constructor assigns this.value = x and a subclass setter for value writes to a subclass private field. Ways to avoid it:
- Do not call overridable methods or setters from a constructor. Have callers run an explicit
init()orrender()after construction. - In the subclass method, guard with a brand check (
if (!(#text in this)) return;) when the early call is expected and harmless. - Compute the value lazily in a getter instead of depending on an initialized field.
Public Fields Shadow Inherited Accessors
Class fields are created with define semantics, the same as Object.defineProperty. They are not assignments. A public field in a subclass therefore puts an own data property on the instance. That property shadows the parent's accessor, and the parent's setter never runs.
class Model {
#title = '';
get title() { return this.#title; }
set title(v) { this.#title = String(v).trim(); }
}
class Article extends Model {
title = ' Draft '; // defines an own data property, skips the setter
}
const a = new Article();
console.log(JSON.stringify(a.title)); // " Draft " (not trimmed)
console.log('value' in Object.getOwnPropertyDescriptor(a, 'title')); // true
class FixedArticle extends Model {
constructor() {
super();
this.title = ' Draft '; // assignment goes through the inherited setter
}
}
const f = new FixedArticle();
console.log(JSON.stringify(f.title)); // "Draft"
console.log(Object.getOwnPropertyDescriptor(f, 'title')); // undefinedThe shadowing data property also outlives construction. Every later a.title = ... writes the data property and skips validation. The bug can go unnoticed for a long time. TypeScript projects sometimes see behavior change here when useDefineForClassFields is switched on, because the older compiled output used assignment.
Static Private Members and `this`
Static members are inherited through the constructor chain (Object.getPrototypeOf(Sub) === Parent), so Sub.someStaticMethod() works. A static private field, however, is installed only on the class that declares it. It is not on the subclass constructor. A parent static method that reads this.#field breaks when a subclass calls it, because this is then the subclass.
class Registry {
static #count = 0;
static register() { return ++this.#count; }
static safeRegister() { return ++Registry.#count; }
}
class SubRegistry extends Registry {}
console.log(Registry.register()); // 1
try {
SubRegistry.register(); // this === SubRegistry, which lacks #count
} catch (err) {
console.log(err instanceof TypeError); // true
}
console.log(SubRegistry.safeRegister()); // 2Inside static methods, refer to static private members by class name (Registry.#count), not through this.
Decision Guide
| Situation | Do this |
|---|---|
| Changing how a subclass reads a value | Override both `get` and `set`, delegating with `super` |
| Subclass needs parent's private state | Parent exposes a getter, setter, or method |
| Subclass wants its own hidden state | Declare a new private field; any name is safe |
| Setting an inherited accessor initially | Assign in the constructor after `super()` |
| Parent constructor calls overridable code | Move the call out of the constructor or guard with `#x in this` |
| Static method uses static private state | Use `ClassName.#x`, not `this.#x` |
Exercise
A Base class has a get/set pair for size backed by #size. A subclass Doubled defines only get size() { return super.size * 2; }. In a module, const d = new Doubled(); d.size = 4; runs. What happens, and how do you fix Doubled so that d.size = 4 makes d.size return 4?
Show answer
Modules are strict, so the assignment throws a TypeError. Doubled.prototype.size is an accessor with no setter, and lookup stops there before it reaches Base's setter. Add set size(v) { super.size = v / 2; }. Base then stores 2 in #size, and the getter returns 2 * 2 = 4.
Exercise
Class Shape declares #color = 'red' and a method getColor() { return this.#color; }. Class Circle extends Shape and declares #color = 'blue' and circleColor() { return this.#color; }. For const c = new Circle(), what do c.getColor() and c.circleColor() return, and why?
Show answer
'red' and 'blue'. Private names are scoped to the class body that declares them, so c holds two separate fields. Shape's method reads Shape's #color, and Circle's method reads Circle's.
Exercise
Class Base has a setter set level(v) that validates v. Subclass Child declares the public field level = 99;. Does the validation run when you call new Child()? Does it run on a later child.level = -1?
Show answer
Neither runs. The class field uses define semantics and creates an own data property level on the instance, so Base's setter is skipped. That own property also shadows the accessor from then on, so later assignments write it directly without validation. Assign this.level = 99 in Child's constructor after super() instead.