Class fields and private members

A class holds fields as well as methods, and the fields come in two kinds. A public field is an own property of every instance, written in the class body without a keyword. A #private member is reachable only from code written inside the same class, and neither Object.keys nor JSON nor a subclass can see it.

This lesson writes both, uses the #name in object check that tells a real instance from a lookalike, and runs code in a static block at the moment the class is defined. It is the first lesson of this part where the language keeps a secret for the programmer rather than asking them to keep it.

Public fields

A public field is written in the class body with a name and an initial value. The initialiser runs for every instance, before the constructor body, in the order the fields are declared, so an array field written there belongs to one instance and not to the class. A field declared without a value is undefined until something writes to it, and it exists as an own key all the same.

The file fields.mjs:

class Task { done = false; tags = []; priority = 1; constructor(title) { this.title = title; } } const a = new Task('write'); const b = new Task('review'); a.tags.push('docs'); a.done = true; a.priority = 3; console.log('the first instance:', JSON.stringify(a)); console.log('the second instance:', JSON.stringify(b)); console.log('the arrays are not shared:', a.tags !== b.tags); console.log('the keys in order:', Object.keys(a).join(','));

node fields.mjs

the first instance: {"done":true,"tags":["docs"],"priority":3,"title":"write"}
the second instance: {"done":false,"tags":[],"priority":1,"title":"review"}
the arrays are not shared: true
the keys in order: done,tags,priority,title

The two instances differ in every field and share not even the array, because the initialiser ran twice. The order of the keys is the order of the declarations, with the field set in the constructor last. A field that held a function call would run that call per instance, which is why a shared array belongs to the class and not to the instance.

#private members

A name that starts with # is a private member, and the hash is part of the name. Code inside the class reads and writes it; code outside cannot reach it at all, and a getter is how the class shows what it wants to show. The member is not an own property with a name of its own, so a copy of the object carries nothing private across. The second program reads the field from outside on purpose, and the file is therefore refused as a whole: that refusal is the point of it, and a linter reports the same line.

The file private.mjs:

class Account { #balance = 0; constructor(owner) { this.owner = owner; } deposit(amount) { this.#balance += amount; return this.#balance; } get balance() { return this.#balance; } static peek(target) { return target.#balance; } } const account = new Account('Ada'); account.deposit(50); account.deposit(25); console.log('the balance:', account.balance); console.log('the own keys:', Object.keys(account).join(',')); console.log('JSON does not see it:', JSON.stringify(account)); console.log('a static method can read it:', Account.peek(account)); try { console.log(Account.peek({ balance: 75 })); } catch (error) { console.log(error.name + ': ' + error.message); }

node private.mjs

the balance: 75
the own keys: owner
JSON does not see it: {"owner":"Ada"}
a static method can read it: 75
TypeError: Cannot read private member #balance from an object whose class did not declare it

The balance came back through the getter and through a static method of the same class, and the two lists of keys and JSON held the public field alone. The error is the runtime side of privacy: the method could ask for the field by name, but the object it was given was not built by this class, so the field is not there. Note that the static method could read the private field of another instance, which is how a class compares two of its own objects.

A read of a private member from outside the class is not a runtime error but a parse error, because the compiler refuses the file before anything runs. The file below is a shortened version of the class from the section before with one line added at the end, and the second file imports it, so the message can be printed as one line.

The file outside.mjs:

class Account { #balance = 0; get balance() { return this.#balance; } } const account = new Account(); console.log(account.balance); console.log(account.#balance);

The file import-outside.mjs:

try { await import('./outside.mjs'); } catch (error) { console.log(error.name + ': ' + error.message); }

node import-outside.mjs

SyntaxError: Private field '#balance' must be declared in an enclosing class

The whole file was refused, so the first line never ran either. The message says exactly what is wrong: a private name may only be used inside the class that declares it. Running the file directly prints the same line after the file name and a caret, and the small importer keeps that report to one line.

The brand check

#code in value answers whether the value really carries that private field, which is a stronger question than instanceof. An object made with Object.create(Vault.prototype) passes the instanceof test and has no private field at all, and a method that trusts the first test would then fail on the second. The check is written inside the class and called as a static method.

The file brand.mjs:

class Vault { #code; constructor(code) { this.#code = code; } static isVault(value) { return #code in value; } } const vault = new Vault('1234'); const fake = Object.create(Vault.prototype); console.log('a real one:', Vault.isVault(vault), vault instanceof Vault); console.log('a copy of the prototype:', fake instanceof Vault); console.log('the brand check is not fooled:', Vault.isVault(fake)); console.log('nor is a plain object:', Vault.isVault({ code: '1234' }));

node brand.mjs

a real one: true true
a copy of the prototype: true
the brand check is not fooled: false
nor is a plain object: false

The fake object was an instance by every test of the chain and failed the check that asks about the field. A plain object failed both. The pattern is worth the two extra lines whenever a value arrives from outside and the class has to be sure of what it is: instanceof reads a prototype, and the brand check reads the object itself.

A static block

A static block is a block of code inside the class body that runs once, when the class is defined, with this set to the class. It is the place for setup that needs more than one statement, such as filling a static object or reading something at load time. Static fields and static methods belong to the class object, not to the instances.

The file static.mjs:

class Config { static defaults = { theme: 'dark' }; static #instances = 0; static { Config.defaults.zoom = 2; console.log('the static block runs once, when the class is defined'); } constructor() { Config.#instances += 1; } static get created() { return Config.#instances; } } console.log('the defaults:', JSON.stringify(Config.defaults)); new Config(); new Config(); console.log('the instances so far:', Config.created); console.log('a static field is not on an instance:', Object.keys(new Config()).length); console.log('the instances after one more:', Config.created);

node static.mjs

the static block runs once, when the class is defined
the defaults: {"theme":"dark","zoom":2}
the instances so far: 2
a static field is not on an instance: 0
the instances after one more: 3

The first line proves the block ran before any instance existed, and the second shows the change it made to a static field. The counter lives on the class and every constructor call adds to it, while an instance owns nothing of it. The count went from two to three because the line that asked for the keys of an instance made one more instance, which is a small warning about putting work in a constructor.

Exercises

  1. Move the tags field of Task in fields.mjs into the constructor and compare the key order. Which of the two places makes the field exist before the constructor runs?
  2. Add a private method to Account in private.mjs that checks the amount and call it from deposit. What does the list of own keys of an instance show?
  3. Write a second class with a #balance field and pass one of its instances to Account.peek. Which error comes back, and why?
  4. Add a public field to Vault in brand.mjs and create the fake object again. Does the brand check change its answer?
  5. Read Config.defaults before the class declaration and move the static block to see when it runs. What does the order of the log lines tell you?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What is the difference between a public field and a #private field?

    Answer

    A private field is reachable only from code inside the same class

    The hash makes the name unusable outside the class body, while a public field is an ordinary own property.

  2. When does a field initialiser run?

    Answer

    For every instance, in declaration order, before the constructor body

    Each instance gets its own copy, which is why an array field is not shared.

  3. What does #code in value answer?

    Answer

    Whether the value carries that private field

    It is the brand check, and it does not read the prototype chain at all.

  4. When does a static block run?

    Answer

    Once, when the class is defined

    The block is part of the class definition, so it runs before any instance exists.

  5. What does this program print? class T { tags = []; constructor(n) { this.name = n; } } const a = new T("a"); const b = new T("b"); a.tags.push("x"); console.log(b.tags.length);

    Answer

    0

    Each instance ran the initialiser, so the two arrays are different objects.

  6. What does this program print? class T { tags = []; constructor(n) { this.name = n; } } const a = new T("a"); console.log(Object.keys(a).join(","));

    Answer

    tags,name

    The field is initialised before the constructor body, so it comes first in the list.

  7. What does this program print? class A { #n = 1; get n() { return this.#n; } } const a = new A(); console.log(a.n, Object.keys(a).length);

    Answer

    1 0

    The getter reads the private field, and the field itself is not an own enumerable key.

  8. What does this program print? class A { static count = 0; constructor() { A.count += 1; } } new A(); new A(); console.log(A.count, Object.hasOwn(new A(), "count"));

    Answer

    2 false

    The static field counts constructor calls and belongs to the class, so an instance does not own it.

  9. What happens when this file is loaded? class A { #n = 1; } const a = new A(); console.log(a.#n);

    Answer

    A SyntaxError, because the private name is used outside its class

    The compiler refuses a private name outside the class body, so nothing in the file runs.

  10. What does this program print? class V { #code = "x"; static has(v) { return #code in v; } } const fake = Object.create(V.prototype); console.log(fake instanceof V, V.has(fake));

    Answer

    true false

    The prototype chain makes the fake an instance, and the brand check still finds no private field.

The code on this page was run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev

Banner image