Sub topic 7
Private Methods and Private Accessors
This chapter assumes you already know how public getters and setters work in classes and how private instance fields like #count behave. The same # prefix also works on methods and on accessors. Private methods let you split a class into small internal helpers. Private accessors let you hide computed or validated state behind a property-like name that only the class can see.
Declaring Private Methods and Accessors
You write a private method like a normal method with # in front of its name. A private accessor is a get or set with a # name. Both are reachable only from code inside the class body, through this.#name or otherInstance.#name.
class Thermostat {
#celsius = 20;
get #fahrenheit() {
return this.#celsius * 9 / 5 + 32;
}
set #fahrenheit(f) {
this.#celsius = (f - 32) * 5 / 9;
}
#clamp(value) {
return Math.min(30, Math.max(10, value));
}
setFromFahrenheit(f) {
this.#fahrenheit = f; // private setter
this.#celsius = this.#clamp(this.#celsius); // private method
}
get reading() {
return `${this.#celsius.toFixed(1)}°C / ${this.#fahrenheit.toFixed(1)}°F`;
}
}
const t = new Thermostat();
t.setFromFahrenheit(212);
console.log(t.reading); // '30.0°C / 86.0°F'
console.log(Object.keys(t)); // []
console.log('clamp' in t); // falseThe public API has two members, setFromFahrenheit and reading. The unit conversion and the clamping rule are internal details. You can rename or rewrite them later without breaking any caller.
How They Differ From Private Fields
Private fields, private methods, and private accessors all use the same # syntax, but they behave differently at runtime.
| Member | Writable with `this.#x = ...` | One copy per instance? | Typical use |
|---|---|---|---|
| Private field `#x = 0` | Yes | Yes, each instance has its own value | Stored state |
| Private method `#x() {}` | No, assigning throws TypeError | No, all instances share one function | Internal helpers |
| Private getter only `get #x()` | No, assigning throws TypeError | Shared function | Read-only derived value |
| Private getter and setter | Yes, runs the setter | Shared functions | Validated or converted internal state |
The runtime checks look like this:
class Demo {
#helper() { return 'ok'; }
get #id() { return 7; }
tryOverwriteMethod() {
try {
this.#helper = () => 'hacked';
} catch (err) {
console.log(err instanceof TypeError); // true
}
}
tryWriteId() {
try {
this.#id = 8; // getter with no setter
} catch (err) {
console.log(err instanceof TypeError); // true
}
}
static sameHelper(a, b) {
return a.#helper === b.#helper;
}
}
const a = new Demo();
const b = new Demo();
a.tryOverwriteMethod();
a.tryWriteId();
console.log(Demo.sameHelper(a, b)); // trueThese errors happen whether or not the code runs in strict mode, because class bodies are always strict. A public getter with no setter behaves the same way inside a class. The difference is that a private one can never be patched from outside.
Common Errors
- Reusing a name. A class cannot declare both
#valueas a field and#value()as a method. That is a SyntaxError. A matchingget #valueandset #valuepair is the only allowed duplicate. - Writing a setter but no getter. If you define only
set #x, then readingthis.#xthrows a TypeError. Add the getter, or make the setter a plain private method such as#setX(v). - Expecting subclasses to see them. Private names belong to the class body that declares them. A subclass cannot call
this.#clamp(), even though the inherited code still can. If a subclass needs the behavior, expose a protected-style public method or pass it in through a constructor parameter. - Calling a private method on a foreign object.
otherObj.#clamp(1)throws a TypeError ifotherObjwas not created by this class.
Exercise
A class declares get #total() { return this.#items.length; } and no setter. A method then runs this.#total = 0;. What happens, and how would you let the class reset the count?
Show answer
The assignment throws a TypeError, because a private getter without a setter is read-only. The count comes from #items, so reset the underlying field, for example this.#items = [];. You could also add a private method such as #reset() { this.#items = []; }.
Exercise
Two instances x and y of the same class each have a private method #run. Inside the class, does x.#run === y.#run evaluate to true or false, and why?
Show answer
True. Private methods are not per-instance copies. Every instance gets the same function object, much like a prototype method, but it is reachable only through the private name.