Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@bakkot
Last active May 23, 2018 19:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bakkot/7fa48f8d20382d53fa1582b92dae9692 to your computer and use it in GitHub Desktop.
Save bakkot/7fa48f8d20382d53fa1582b92dae9692 to your computer and use it in GitHub Desktop.
// 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