【发布时间】:2020-07-28 22:04:48
【问题描述】:
考虑以下代码:
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
myOverrideMethod() 的重写方法在“基”类的构造函数中调用。由于this 指向MyClass 的一个实例,所以派生类中被覆盖的方法被正确调用。 mySpecificMethod() 的常规方法调用成功,而调用#myPrivateMethod() 的私有字段会抛出以下“TypeError”:
未捕获的类型错误:无法从类未声明的对象中读取私有成员
#myPrivateMethod
错误消息并未将问题传达为私有字段访问冲突,而是唤起了this 尚未引用MyClass 的实例但仍引用@ 的实例987654330@!但是,这是为什么呢?如何成功调用#myPrivateMethod()的私有方法呢?
【问题讨论】:
-
永远不要从构造函数中调用可覆盖的方法,也不要为方法使用类字段。
标签: javascript inheritance constructor overriding private-members