假设我有以下 JavaScript 代码
class Parent {
constructor () {
console.log("parent");
}
}
class Child1 extends Parent {
constructor() {
console.log("child 1");
super();
}
}
class Child2 extends Parent {
constructor() {
console.log("child 2");
super();
}
}
const c1 = new Child1; // Output: 'child 1' then 'parent'
const c2 = new Child2; // Output: 'child 2' then 'parent'
现在,是否可以从班级内部知道
Parent
哪个子班级调用了它?像这样的东西:
class Parent {
constructor () {
console.log("parent");
// If this class has a child, what's the child?
}
}
谢谢你
通常,为子类获得正确行为的方法是拥有每个子类都重写的方法。每个子类都有其正确的实现。
或者,您可以根据各种预期的子类类型检查
this
的类型。与其比较类类型,不如拥有一个方法并重写它。
您还可以将子类名称或枚举器作为参数传递给超类的构造函数。同样,最好有一个方法并重写它。