Last active
July 16, 2022 18:22
-
-
Save getify/a784ca38f3cf614fd6199686c71738ca to your computer and use it in GitHub Desktop.
strange inconsistency (between members and statics) with privates+subclassing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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