javascript 哪个子类扩展了父类

svmlkihl  于 12个月前  发布在  Java
关注(0)|答案(2)|浏览(94)

假设我有以下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?
  }
}

谢谢你

kuarbcqp

kuarbcqp1#

通常,为子类获得正确行为的方法是让每个子类都重写一个方法。每个子类都有其正确的实现。
或者,您可以根据各种预期的子类类型检查this的类型。与其比较类类型,不如拥有一个方法并覆盖它。
也可以将子类名称或枚举数作为参数传递给超类的构造函数。同样,最好有一个方法并覆盖它。

gwo2fgha

gwo2fgha2#

你在找console.log(Object.getPrototypeOf(this));吗?

class Parent {
  constructor () {
    console.log("parent");
    
    console.log(Object.getPrototypeOf(this)); // Should log Child2: {} or Child 1: {}
  }
}

相关问题