Sub topic 7
Private Methods and Private Accessors
This chapter assumes you already know how private instance fields (#field) work, how public getters and setters behave in classes, and how this is bound when a method is called. Private methods and private accessors use the same # syntax as private fields, but they have their own rules about where they live, what you may assign to them, and what happens when they are called on the wrong object.
Why Private Behavior, Not Just Private Data
Private fields hide state. A class usually also has helper logic that outside code should not call: validation routines, formatting helpers, or values that are computed internally and never shown to callers. Before #, that logic went into public methods named with a leading underscore, or into functions outside the class. Neither option was enforced.
A private method is a method whose name starts with #. Only code inside the class body can call it. A private accessor is a getter or setter whose name starts with #, and it follows the same rule. You declare both the same way as their public versions, with # added to the name.
class Cart {
#items = new Map(); // name -> { price, qty }
add(name, price, qty = 1) {
this.#assertPositiveInt(qty);
const existing = this.#items.get(name);
if (existing) {
existing.qty += qty;
} else {
this.#items.set(name, { price, qty });
}
return this;
}
#assertPositiveInt(n) {
if (!Number.isInteger(n) || n <= 0) {
throw new RangeError(`Quantity must be a positive integer, got ${n}`);
}
}
get #subtotal() {
let sum = 0;
for (const { price, qty } of this.#items.values()) {
sum += price * qty;
}
return sum;
}
get total() {
const sub = this.#subtotal;
return sub >= 100 ? sub - 10 : sub; // flat discount over 100
}
}
const cart = new Cart();
cart.add('book', 30, 2).add('pen', 5, 10);
console.log(cart.total); // 100
try {
cart.add('mug', 8, 0);
} catch (err) {
console.log(err.message); // Quantity must be a positive integer, got 0
}The public surface is add and total. Outside code cannot call the validator #assertPositiveInt or read the intermediate #subtotal. Writing cart.#subtotal outside the class body is a SyntaxError at parse time, so the script never runs.
Private Accessor Pairs
A private getter and a private setter can share a name, just as public ones can. Reading this.#name calls the getter, and assigning to it calls the setter. Compound assignment operators like += call both: first the getter, then the setter with the new value.
class Thermostat {
#celsius = 20;
get #fahrenheit() {
return this.#celsius * 9 / 5 + 32;
}
set #fahrenheit(f) {
this.#celsius = (f - 32) * 5 / 9;
}
raiseByFahrenheit(delta) {
this.#fahrenheit += delta; // get (68), then set (86)
return this.#celsius;
}
}
const t = new Thermostat();
console.log(t.raiseByFahrenheit(18)); // 30This pattern lets the class work internally in whichever unit suits each method while storing the value only once. Nothing about Fahrenheit is visible to callers.
A getter and setter pair is the only case where two private declarations may share a name. Declaring #x as both a field and a method, or as two methods, is a SyntaxError. A static getter and an instance setter with the same private name is also a SyntaxError, because they would live on different objects.
Where Private Methods Live
Public methods sit on the class's prototype and are shared through the prototype chain. Private methods do not use the prototype at all. When the constructor runs, every private method and accessor is attached to the new instance as a hidden internal entry. This entry is part of what the spec calls the object's "brand." The function object itself is created once, when the class is defined, and every instance shares it.
That design has observable consequences.
class Widget {
#render() { return 'rendered'; }
get #id() { return 7; }
tryReassignMethod() {
try {
this.#render = () => 'hacked';
} catch (err) {
return err.constructor.name;
}
}
tryWriteGetterOnly() {
try {
this.#id = 8;
} catch (err) {
return err.constructor.name;
}
}
static sameFunction(a, b) {
return a.#render === b.#render;
}
}
const w = new Widget();
console.log(Object.getOwnPropertyNames(Widget.prototype));
// [ 'constructor', 'tryReassignMethod', 'tryWriteGetterOnly' ]
console.log(Reflect.ownKeys(w)); // []
console.log(w.tryReassignMethod()); // TypeError
console.log(w.tryWriteGetterOnly()); // TypeError
console.log(Widget.sameFunction(w, new Widget())); // trueThe table summarizes how each kind of private element behaves.
| Element | Declared as | Readable | Writable | Installed |
|---|---|---|---|---|
| Private field | `#x = 1;` | Yes | Yes | Per instance, in declaration order |
| Private method | `#m() {}` | Yes, returns the function | No, assignment throws `TypeError` | Per instance, before any field initializer |
| Private getter only | `get #g() {}` | Yes, runs the getter | No, assignment throws `TypeError` | Per instance, before any field initializer |
| Private setter only | `set #s(v) {}` | No, reading throws `TypeError` | Yes, runs the setter | Per instance, before any field initializer |
| Private getter and setter | both | Yes | Yes | Per instance, before any field initializer |
Private methods cannot be replaced, deleted, or monkey-patched. This is deliberate. You can be sure this.#render() always runs the code written in the class body, and no other code can intercept it.
Initialization Order
All private methods and accessors are installed on the instance before any field initializer runs. This means field initializers can call private methods, even ones declared further down in the class body.
class Session {
#id = this.#generateId();
#createdAt = Date.now();
#generateId() {
return Math.random().toString(36).slice(2, 10);
}
get id() {
return this.#id;
}
}
const s = new Session();
console.log(typeof s.id, s.id.length > 0); // string trueThe reverse is not safe. If a private method reads a private field that has not been initialized yet, it throws a TypeError. In the example above, a #generateId that read this.#createdAt would fail, because #id is initialized first. Fields are initialized top to bottom, so order them so that dependencies come first.
In a subclass, the base class's private methods are installed while super() runs, and the subclass's own private methods are installed right after super() returns. Calling any of them before super() is impossible anyway, because this is not yet available.
What Happens When You Evaluate `this.#name`
Private-name access is checked in two stages. The parser first confirms that the name is declared in an enclosing class body. At run time, the engine then checks that the object actually carries that private element.
Because of this check, private methods are also a type guard. If a public method calls this.#helper() and someone invokes that public method with a different this (for example with Widget.prototype.tryReassignMethod.call({})), the call throws instead of quietly running on the wrong object. A later chapter shows how to test for the brand without throwing, using #name in obj.
Losing `this` When Extracting a Private Method
Reading this.#format gives you a plain function. Calling it on its own loses the receiver, just as it would with a public method. Inside the function, this is undefined (class code is always strict), so the first private access throws.
class Logger {
#prefix = '[app]';
#format(msg) {
return `${this.#prefix} ${msg}`;
}
formatterBroken() {
return this.#format;
}
formatter() {
return (msg) => this.#format(msg);
}
formatterBound() {
return this.#format.bind(this);
}
}
const log = new Logger();
try {
log.formatterBroken()('hi');
} catch (err) {
console.log(err instanceof TypeError); // true
}
console.log(log.formatter()('hi')); // [app] hi
console.log(log.formatterBound()('hi')); // [app] hiUse an arrow wrapper or bind whenever you pass a private method as a callback, for example to addEventListener, setTimeout, or Array.prototype.map. Another common option is a private field that holds an arrow function, such as #onClick = () => { ... }. It captures this automatically. The cost is one new function per instance instead of one shared function.
No Dynamic Access
Private names are lexical identifiers, not strings. You cannot compute them, and they share nothing with string keys that happen to look the same.
class Demo {
#secret() { return 'private'; }
check() {
this['#secret'] = 'public string key';
return [this.#secret(), this['#secret']];
}
}
console.log(new Demo().check()); // [ 'private', 'public string key' ]this['#secret'] creates an ordinary public property named with the string "#secret". It has nothing to do with the private method. You cannot iterate over private members, look them up by a variable name, or reach them through Reflect or Object.getOwnPropertyDescriptor. If you need dispatch by name, keep a private Map of handlers, or use a switch statement in a private method.
Choosing Where Helper Logic Should Go
Private methods are not always the best place for helper code. Use this table to decide.
| Option | Needs `this`? | Hidden from callers | Testable directly | Overridable by subclasses |
|---|---|---|---|---|
| Private method `#m()` | Yes, and can read private fields | Yes, enforced | No | No |
| Module-level function | No, takes arguments | Yes, if not exported | Yes, if exported for tests | No |
| Symbol-keyed method `[sym]()` | Yes | Partly; reachable via `Object.getOwnPropertySymbols` | Yes | Yes |
| Public method with `_` prefix | Yes | No, convention only | Yes | Yes |
Use a private method when the logic needs access to private fields and must not be overridden or called from outside. Use a module-level function for pure helpers that do not touch instance state. Use a symbol-keyed or underscore method when subclasses are meant to override the behavior, because subclasses cannot see or replace a private method.
Exercises
Exercise
A class declares get #total() { ... } and no setter. A method runs this.#total += 5. What happens, and why?
Show answer
It throws a TypeError. The compound assignment first calls the getter, which succeeds, and then tries to set #total with the result. With no private setter, the write throws TypeError. Add a set #total(v) or write to the underlying private field directly.
Exercise
In a class with #name = this.#describe(); declared first and #label = 'item'; declared second, #describe() returns ` ${this.#label}! . Does new` succeed? How would you fix it?
Show answer
It throws a TypeError. Private methods are installed before field initializers run, so calling #describe works, but #label has not been initialized yet when #name's initializer runs. Declare #label before #name, so the fields are initialized in dependency order.
Exercise
You write button.addEventListener('click', this.#handleClick) in a constructor, and #handleClick reads this.#count. Clicking throws a TypeError. Give two fixes and the trade-off between them.
Show answer
When the listener fires, this is the button element, not the instance, so reading #count fails the brand check. One fix is to pass this.#handleClick.bind(this), or an arrow wrapper (e) => this.#handleClick(e), and keep the shared method. The other fix is to declare #handleClick = (e) => { ... } as a private field holding an arrow function. That captures this automatically, but it creates one new function per instance, while a private method shares a single function across all instances. Either way, keep a reference to the function you passed if you need to call removeEventListener later.