without constructor, is there a way to get child class name in JavaScript?

53 views Asked by At

I have a class A and a child class B . now i want to print child class name from a static method of parent class. but both of them doesn't use constructor or new keyword.

Class A {
  static run() {
    console.log("child class name");
  }
}

class B extends A {}

B.run();

B.run() returning the Class name of B

1

There are 1 answers

0
Ninhache On

I'm not sure i've really understood your question, let me know if i'm wrong..

You could simply use this.name (in the A class) to make B.run returns "B"
As following :

class A {
  static run() {
    console.log(this.name);
  }
}

class B extends A {}

A.run();
B.run();

this.name is available because we're in a static context, in a non-static method you would've use this.constructor.name ..