Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 1

Private fields and brand checks (#x in obj) in JavaScript

79 A wallet class with # fields, a static count and a brand check

fair

Write a wallet class whose balance lives in a private #kobo field, with a private method that validates, a static counter that tracks how many were made, a static factory, and a brand check written as #kobo in value. Then show that the private field is genuinely unreachable from outside and that a detached method loses its this.

Stuck? Three hints, smallest first
  1. 1. A # name is not a string key: it is not in Object.keys, not in JSON.stringify, and not reachable with brackets.
  2. 2. static #count belongs to the class, and a static method is the only thing that can read it.
  3. 3. #kobo in value is a true brand check: it answers "was this object built by this class" without throwing.

The answer

class Wallet {
  #kobo = 0;
  static #opened = 0;

  constructor(kobo = 0) {
    this.#kobo = Wallet.#check(kobo);
    Wallet.#opened++;
  }

  static #check(kobo) {
    if (!Number.isInteger(kobo) || kobo < 0) throw new RangeError('kobo must be a whole number of at least zero');
    return kobo;
  }

  static fromNaira(naira) {
    return new Wallet(Math.round(naira * 100));
  }

  static get opened() {
    return Wallet.#opened;
  }

  static isWallet(value) {
    return #kobo in value;
  }

  get naira() {
    return this.#kobo / 100;
  }

  credit(kobo) {
    this.#kobo += Wallet.#check(kobo);
    return this;
  }

  toJSON() {
    return { kobo: this.#kobo, naira: this.naira };
  }
}

const a = new Wallet(150000);
const b = Wallet.fromNaira(62.505);
a.credit(50000).credit(1);

const balances = [a.toJSON(), b.toJSON()];
const openedCount = Wallet.opened;
const hiddenFromReflection = [Object.keys(a), JSON.stringify(b), 'kobo' in a];

const brands = [Wallet.isWallet(a), Wallet.isWallet({ kobo: 1 }), Wallet.isWallet(Wallet.prototype)];

let refused;
try {
  new Wallet(-5);
} catch (error) {
  refused = error.constructor.name;
}

let outside;
try {
  outside = new Function('return (w) => w.#kobo;');
} catch (error) {
  outside = error.constructor.name;
}

const detached = a.credit;
let lostThis;
try {
  detached(1);
} catch (error) {
  lostThis = error.constructor.name;
}

console.log('balances:', balances, '| opened:', openedCount);
console.log('hidden  :', hiddenFromReflection);
console.log('brands  :', brands, '| refused:', refused);
console.log('outside :', outside, '| detached:', lostThis);

Output


      
8 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 8 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

8 checks

test('the private field holds the truth and a getter exposes a view of it', balances, [{ kobo: 200001, naira: 2000.01 }, { kobo: 6251, naira: 62.51 }]);
test('a static private counter survives across every instance', openedCount, 2);
test('nothing about #kobo shows up in keys, in JSON, or to the in operator', hiddenFromReflection, [[], '{"kobo":6251,"naira":62.51}', false]);
test('so toJSON is how a class with private state gets serialised at all', JSON.parse(JSON.stringify(a)), { kobo: 200001, naira: 2000.01 });
test('the brand check is true for instances and false for a look-alike', brands, [true, false, false]);
test('a private static validator guards every entry point, constructor included', refused, 'RangeError');
test('reading a # field from outside the class body is a syntax error, not a runtime one', outside, 'SyntaxError');
test('and a detached method has no this in strict mode, so the private read throws', lostThis, 'TypeError');

# privacy is real, not a convention. The name is lexically scoped to the class body, so there is no string key to guess, nothing in Object.keys or JSON.stringify, and no way to reach it from outside — the attempt is rejected by the parser, which is why the assertion above catches a SyntaxError rather than a TypeError. The cost is that serialisation becomes your job, and toJSON is the usual answer.

static #opened lives on the class, so it counts across all instances and only static members can read it. Pairing it with a static factory such as fromNaira gives you named constructors without touching the real one, and a private static validator means every path in — constructor, factory, credit — is checked by the same code.

Two sharp edges. #kobo in value is the brand check to use: instanceof can be fooled by a changed prototype, while the in form asks whether this class actually installed its field, and it cannot throw. And because credit reads a private field through this, pulling it off the instance breaks it: const f = a.credit; f(1) gets this === undefined under strict mode and throws. Pass () => a.credit(1) or a bound method when handing a class method to a callback.

Newsletter

New writing, when it lands.

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