skip to Main Content

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

2

Answers


  1. 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.

    Login or Signup to reply.
  2. Are you looking for console.log(Object.getPrototypeOf(this)); ?

    class Parent {
      constructor () {
        console.log("parent");
        
        console.log(Object.getPrototypeOf(this)); // Should log Child2: {} or Child 1: {}
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search