Search code examples
javascriptclassinheritanceparent-childes6-class

Which child class extended the parent class


Assume I have the following JavaScript code

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'

Now, is it possible to know, from within the class Parent which child class called it? Something like this:

class Parent {
  constructor () {
    console.log("parent");
    
    // If this class has a child, what's the child?
  }
}

Thank you


Solution

  • Normally, the way to get the correct behaviour for your sub-class is to have a method that every sub-class overrides. Each sub-class has its correct implementation.

    Alternatively, you could check the type of this against the various expected sub-class types. Rather than comparing class-types, it's still preferable to have a method and to override it.

    You could also pass a sub-class name or an enumerator as a parameter to the super-class' constructor. Again, it's preferable to have a method and to override it.