private static subclassing.js

May 23, 2018 ยท View on GitHub

// code which works

class Box { #producerStamp;

constructor(items) { this.items = items; }

get producerStamp() { return this.#producerStamp; }

static of(...items) { const box = new this(items); box.#producerStamp = 'made by: ' + this.name; return box; }

static from(items) { const box = new this(items); box.#producerStamp = 'made by: ' + this.name; return box; } }

class RedBox extends Box {}

console.log(Box.of(0).producerStamp); // 'made by: Box'

console.log(RedBox.of(0).producerStamp); // 'made by: RedBox'

// reasonable refactoring of that, which doesn't:

class Box { #producerStamp;

constructor(items) { this.items = items; }

get producerStamp() { return this.#producerStamp; }

static #makeWithStamp(items) { const box = new this(items); box.#producerStamp = 'made by: ' + this.name; return box; }

static of(...items) { return this.#makeWithStamp(items); }

static from(items) { return this.#makeWithStamp(items); } }

class RedBox extends Box {}

console.log(Box.of(0).producerStamp); // 'made by: Box'

console.log(RedBox.of(0).producerStamp); // throws an error at this.#makeWithStamp, complaining that #makeWithStamp is missing on RedBox