假设我有以下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?
}
}
谢谢你
2条答案
按热度按时间kuarbcqp1#
通常,为子类获得正确行为的方法是让每个子类都重写一个方法。每个子类都有其正确的实现。
或者,您可以根据各种预期的子类类型检查
this
的类型。与其比较类类型,不如拥有一个方法并覆盖它。也可以将子类名称或枚举数作为参数传递给超类的构造函数。同样,最好有一个方法并覆盖它。
gwo2fgha2#
你在找
console.log(Object.getPrototypeOf(this));
吗?