Skip to content

Instantly share code, notes, and snippets.

@getify
Last active July 16, 2022 18:22
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 getify/a784ca38f3cf614fd6199686c71738ca to your computer and use it in GitHub Desktop.
Save getify/a784ca38f3cf614fd6199686c71738ca to your computer and use it in GitHub Desktop.
strange inconsistency (between members and statics) with privates+subclassing
class Point2d {
#ID = null
constructor(id) {
this.#ID = id;
}
getID() {
return this.#ID;
}
}
class Point3d extends Point2d {
printID() {
console.log(`ID: ${this.getID()}`);
}
}
var point = new Point3d(42);
point.getID();
// 42
point.printID();
// ID: 42
// ***************
Object.hasOwn(Point2d.prototype,"getID"); // true
Object.hasOwn(Point3d.prototype,"getID"); // false
Object.hasOwn(point,"getID"); // false
class Point2d {
static #ID = 42
static getID() {
return this.#ID; // <--- this line breaks when subclassing!
}
}
class Point3d extends Point2d {
static printID() {
console.log(`ID: ${this.getID()}`);
}
}
Point2d.getID();
// 42
Point3d.getID();
// TypeError: Cannot read private member #ID from
// an object whose class did not declare it
Point3d.printID();
// TypeError: Cannot read private member #ID from
// an object whose class did not declare it
// ***************
Object.hasOwn(Point2d,"getID"); // true
Object.hasOwn(Point3d,"getID"); // false
class Point2d {
static #ID = 42
static getID() {
// here, swap the `this` reference
// with the `Point2d` class name
//
// return this.#ID;
return Point2d.#ID;
}
}
class Point3d extends Point2d {
static printID() {
console.log(`ID: ${this.getID()}`);
}
}
Point2d.getID();
// 42
Point3d.getID();
// 42
Point3d.printID();
// ID: 42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment