Which child class extended the parent class

72 views Asked by At

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

3

There are 3 answers

0
SmellyCat On BEST ANSWER

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.

0
Gaganpreet On

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: {}
  }
}
1
Peter Seliger On

From my above comment ...

"A much easier / more direct way of retrieving/accessing this information was to make use of new.target ... class Parent { constructor () { console.log(new.target); console.log("parent"); } }"

The OP's example code then changes to ...

class Parent {
  constructor () {
    console.log(`${ new.target.name } ... ${ new.target }`);
    console.log("parent");
    console.log("\n");
  }
}

class Child1 extends Parent {
  constructor() {
    console.log("child 1 ...");
    super();
  }
}
class Child2 extends Parent {
  constructor() {
    console.log("child 2");
    super();
  }
}
const c1 = new Child1;
const c2 = new Child2;
.as-console-wrapper { min-height: 100%!important; top: 0; }

Note

While the above code answers the OP's question, it might not be the best solution for the OP's class design / type system. The real question is ...

What does the OP need the very information for?