Skip to content

Instantly share code, notes, and snippets.

@bakkot bakkot/private static subclassing.js Secret
Last active May 23, 2018

Embed
What would you like to do?
// 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.