Static Members and Private Fields
Static members belong to the class rather than to instances, and private fields are the first genuine privacy JavaScript has ever had.
static puts a property or method on the class itself, which is why it inherits through the second link extends creates. A # field is private at the syntax level: unreachable from outside, undeletable, and checked before the code runs.
EXERCISE
1static: Belonging to the Class, Not the Instance
Some things are about the type as a whole rather than about any one object of it, and static is where they go.
The difference in one example:
class Circle {
static PI = 3.14159;
constructor(radius) {
this.radius = radius;
}
area() {
return Circle.PI * this.radius ** 2;
}
static fromDiameter(d) {
return new Circle(d / 2);
}
}
console.log(Circle.PI); // 3.14159
console.log(Circle.fromDiameter(10).radius); // 5
const c = new Circle(5);
console.log(c.PI); // undefined
console.log(c.fromDiameter); // undefined
PI and fromDiameter sit on Circle itself. Instances do not inherit them, because an instance's chain goes through Circle.prototype, and static members are not on Circle.prototype. They are on Circle.
Which is exactly the split you would make by hand:
function Circle(radius) {
this.radius = radius;
}
Circle.PI = 3.14159; // static: on the function
Circle.fromDiameter = function (d) {
return new Circle(d / 2);
};
Circle.prototype.area = function () {
/* ... */
}; // instance: on the prototype
No new mechanism. static puts the property on the constructor function, which is something you could always do.
The most common real use is a named alternative constructor:
class Duration {
constructor(ms) {
this.ms = ms;
}
static fromSeconds(s) {
return new Duration(s * 1000);
}
static fromMinutes(m) {
return new Duration(m * 60_000);
}
}
console.log(Duration.fromMinutes(2).ms); // 120000
A constructor can only have one signature. Static factory methods give you as many named ways in as you need, and the name says what the argument means, which new Duration(120000) does not.
And static members inherit, through the second link from the last lesson:
class Base {
static create() {
return new this();
}
}
class Child extends Base {}
console.log(Child.create() instanceof Child); // true
Child.create was found by walking from Child to Base, which works because extends linked the two constructor functions. And new this() builds a Child, because in a static method this is the class it was called on.
Pro Tip: Ask whether the thing needs an instance to make sense. A radius belongs to one circle; the value of pi does not. A method that reads
this.somethingbelongs on the prototype; a method that only uses its arguments, or that builds an instance, usually belongs on the class.
EXERCISE
2Private Fields, and Why # Instead of _
The underscore convention was always a request. A hash is enforced by the language before your code runs.
The old convention, and its problem:
class Account {
constructor(balance) {
this._balance = balance; // "please do not touch this"
}
deposit(n) {
this._balance += n;
}
}
const a = new Account(100);
console.log(a._balance); // 100, nothing stopped anyone
a._balance = -999; // including setting it to nonsense
_balance is an ordinary property with a naming convention attached. It shows up in Object.keys, in JSON.stringify, in the debugger and in autocomplete. Nothing enforces anything.
The real thing:
class Account {
#balance;
constructor(balance) {
this.#balance = balance;
}
deposit(n) {
this.#balance += n;
return this.#balance;
}
get balance() {
return this.#balance;
}
}
const a = new Account(100);
console.log(a.deposit(50)); // 150
console.log(a.balance); // 150
// console.log(a.#balance);
// SyntaxError: Private field '#balance' must be declared in an enclosing class
Note that last error is a SyntaxError, not a runtime one. The code does not run at all. This is unusual for a dynamic language and it is deliberate: the hash is part of the identifier, not a string key, so the engine can check it while parsing.
Which means it really is invisible from outside:
const a = new Account(100);
console.log(Object.keys(a)); // []
console.log(JSON.stringify(a)); // {}
console.log(Object.getOwnPropertyNames(a)); // []
// delete a.#balance; // SyntaxError
Private fields do not appear in any reflection, cannot be serialised, and cannot be deleted. The underscore convention gave you none of that.
Methods and static members can be private too:
class Order {
#items = [];
static #count = 0;
constructor() {
Order.#count += 1;
}
#total() {
return this.#items.reduce((sum, i) => sum + i.price, 0);
}
summary() {
return `${this.#items.length} items, ${this.#total()}`;
}
static get created() {
return Order.#count;
}
}
const o = new Order();
console.log(o.summary()); // 0 items, 0
console.log(Order.created); // 1
And one genuinely useful trick, the in check:
class Account {
#balance = 0;
static isAccount(obj) {
return #balance in obj;
}
}
console.log(Account.isAccount(new Account())); // true
console.log(Account.isAccount({})); // false
#balance in obj asks whether that object carries this exact private field. Unlike instanceof, it cannot be faked by rewiring a prototype, which makes it the most reliable "is this really one of mine" check available.
Pro Tip: Reach for
#whenever a field is an implementation detail. The payoff is not secrecy for its own sake: it is that you can change or remove that field later knowing with certainty that no other code depends on it, because no other code was able to reach it.
EXERCISE
3Static Blocks, and Choosing Where Things Live
A static block runs once when the class is defined, and the wider question is when a static member is the right home at all.
Static fields handle simple values. When setting one up takes more than an expression, a static initialisation block runs once, when the class is first evaluated.
The block, and why it exists:
class Config {
static settings;
static loadedAt;
static {
const raw = { retries: "3", debug: "false" };
Config.settings = {
retries: Number(raw.retries),
debug: raw.debug === "true",
};
Config.loadedAt = Date.now();
}
}
console.log(Config.settings); // { retries: 3, debug: false }
Everything inside runs a single time, in order, before the class is used. Inside the block this is the class itself, so this.settings works as well as Config.settings.
It can also reach private static fields, which a plain field initialiser cannot easily set up:
class Registry {
static #items = new Map();
static {
Registry.#items.set("default", { enabled: true });
}
static get(key) {
return Registry.#items.get(key);
}
}
console.log(Registry.get("default")); // { enabled: true }
Now the more important question: where should a thing live at all?
// 1. INSTANCE property: differs per object.
class Order {
constructor(id) {
this.id = id;
}
}
// 2. PROTOTYPE method: same logic, needs `this`.
class Order {
total() {
return this.items.length;
}
}
// 3. STATIC member: about the type, not any one object.
class Order {
static MAX_ITEMS = 50;
static fromJSON(j) {
/* ... */
}
}
// 4. MODULE scope: about neither, and needs no class at all.
const TAX_RATE = 0.18;
function formatCurrency(n) {
return `Rs ${n.toFixed(2)}`;
}
The fourth is the one people skip, and it is worth pausing on. A helper that takes its inputs as arguments and returns a value does not belong on a class simply because it is used by one. Exporting it from the module keeps it testable on its own and importable without dragging the class along.
A rule of thumb that holds up:
// Does it read `this`? -> prototype method
// Does it build or describe the
// type as a whole? -> static
// Does it vary per object? -> instance field
// Neither? -> plain module function
Static members are easy to over-use, because putting a function "inside the class" feels tidier than leaving it loose in the file. It usually is not. Reserve static for alternative constructors, type-level constants and registries, and let ordinary functions stay ordinary functions.
