Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 1

Private class fields and methods in JavaScript

44 Private # fields and # methods

fair

Give an account a private balance, a private method that writes an audit line, and a private static counter. Then prove that reaching for #kobo from outside the class is not undefined but a syntax error, and use #kobo in value as a brand check.

Stuck? Three hints, smallest first
  1. 1. A # name is only in scope inside the class body. Outside it the parser rejects the code, so the failure has to be produced with new Function and caught.
  2. 2. Private methods work the same way as private fields, and neither appears on the prototype.
  3. 3. #kobo in value asks "was this object built by this class?" and returns false instead of throwing.

The answer

class Account {
  #kobo = 0;
  #log = [];
  static #opened = 0;

  constructor(owner) {
    this.owner = owner;
    Account.#opened++;
  }
  deposit(kobo) {
    this.#record('in', kobo);
    this.#kobo += kobo;
    return this;
  }
  get balance() {
    return this.#kobo;
  }
  get history() {
    return [...this.#log];                    // a copy, so callers cannot edit it
  }
  #record(kind, kobo) {                       // private method
    this.#log.push(`${kind}:${kobo}`);
  }
  static has(value) {
    return #kobo in value;                    // brand check, never throws
  }
  static get opened() {
    return Account.#opened;
  }
}

const parses = (src) => { try { new Function(src); return 'parsed'; } catch (e) { return e.constructor.name; } };

const tunde = new Account('tunde').deposit(500000);
const ada = new Account('ada');
const outsideAccess = parses('class A { #x = 1; } const a = new A(); return a.#x;');
const insideAccess = parses('class A { #x = 1; read() { return this.#x; } } return new A().read();');
const impostor = { owner: 'tunde', balance: 500000 };

console.log('balance  :', tunde.balance, '| history:', tunde.history);
console.log('own keys :', Object.keys(tunde), '| JSON:', JSON.stringify(tunde));
console.log('a.#x outside the class parses?', outsideAccess, '| inside?', insideAccess);
console.log('brand    :', Account.has(tunde), Account.has(impostor));
console.log('opened   :', Account.opened);

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('the deposit landed in the private field', tunde.balance, 500000);
test('which is not an own key', Object.keys(tunde), ['owner']);
test('and does not serialise', JSON.stringify(tunde), '{"owner":"tunde"}');
test('reading #kobo from outside is a syntax error, not undefined', outsideAccess, 'SyntaxError');
test('the same access inside the body is fine', insideAccess, 'parsed');
test('a private method is not on the prototype either', Object.getOwnPropertyNames(Account.prototype), ['constructor', 'deposit', 'balance', 'history']);
test('but it ran, and wrote the audit line', tunde.history, ['in:500000']);
test('#kobo in x answers the brand question without throwing', [Account.has(tunde), Account.has(impostor)], [true, false]);
test('a private static counted both constructions, and the second account has its own balance', [Account.opened, ada.balance], [2, 0]);

_name was always a request. #name is enforced by the parser: the fourth assertion shows the failure arriving before the program runs, which is why no amount of Object.keys, JSON.parse(JSON.stringify(...)) or Reflect.ownKeys will find it. That is stronger than the old WeakMap-keyed-by-instance trick and far cheaper.

The brand check is the part people miss. value.#kobo on a foreign object throws a TypeError, so it is useless for asking "is this one of mine?" — but #kobo in value answers false quietly. It is a truer test than instanceof, which an Object.create(Account.prototype) would pass while having no private field at all.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.