Consider the following code:
class MyBase {
constructor(b) {
this.myOverrideMethod(b);
}
myOverrideMethod(b) {}
}
class MyClass extends MyBase {
constructor(b) {
super(b);
}
myOverrideMethod(b) {
if (b) {
this.mySpecificMethod();
} else {
this.#myPrivateMethod();
}
}
mySpecificMethod() {
console.log('mySpecificMethod');
}
#myPrivateMethod = () => {
console.log('#myPrivateMethod');
};
}
new MyClass(true); // <-- "mySpecificMethod"
new MyClass(false); // <-- Uncaught TypeError: Cannot read private member #myPrivateMethod
// from an object whose class did not declare it
The overridden method of myOverrideMethod()
is called in the constructor of the "base" class. Since this
points to an instance of MyClass
, the overrided method in the derived class is invoked correctly. The regular method of mySpecificMethod()
gets called successfully, while invoking the private field of #myPrivateMethod()
throws the following "TypeError":
Uncaught TypeError: Cannot read private member
#myPrivateMethod
from an object whose class did not declare it
The error message does not convey the issue as being a private field access violation, but rather evokes the this
does not yet reference an instance of MyClass
but still references an instance of MyBase
! However, why is that and how to successfully invoke the private method of #myPrivateMethod()
?