skip to Main Content

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

2

Answers


  1. Checking the prototype is one possible way?

    class A {
      static run() {
      console.log(this.prototype instanceof A ? 'B' : 'A');
      }
    }
    
    class B extends A {}
    
    B.run();
    A.run();
    Login or Signup to reply.
  2. 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 ..

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search