15

I am trying to print out the name of class B or C in it's super class (A). Is there a way to infer this somehow from the context? Do I have to pass in the names into super as a parameter or is there a better way of doing this?

class A {
  constructor(){
    console.log(klass_name) // klass_name is some code to get the name of class B,C
  }
}

class B extends A {
  constructor() {
    super();
  }
}

class c extends A {
  super();
}
Ryan-Neal Mes
  • 6,003
  • 7
  • 52
  • 77

3 Answers3

25

Yes, there are two ways you can access it where you've shown:

  • this.constructor.name (assuming nothing has messed around with it), which you can use anywhere that has access to the instance
  • new.target.name (only available in the constructor, new.target is undefined in function calls that aren't part of a new operation)

But other than logging purposes and such, it's rare for the superclass to need to know anything about the subclass.

Example:

class A {
  constructor(){
    console.log("this.constructor.name = " + this.constructor.name);
    console.log("new.target.name = " + new.target.name);
  }
}

class B extends A {
}

class C extends A {
}

new C;

The constructor property is automatically set up on a class's prototype to refer to the class's constructor, and as of ES2015 functions (including constructors) have a name property on them giving their name. Since the instance inherits from the prototype, you can use constructor on it to access that constructor and its name.

The new.target metaproperty is available in functions to indicate what the target function of the new expression was.


Side note: When your subclass constructor is nothing but a call to the superclass constructor, you can leave it off entirely. The JavaScript engine will add one for you.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • `this.constructor.name` works perfectly. I need the base class in my scenario, just simplified for post. Thx – Ryan-Neal Mes Dec 12 '16 at 10:00
  • 1
    I want to get the name of the child class in static method of parent class – Amarjit Singh Jan 19 '19 at 19:44
  • 1
    @AmarjitSingh - I suggest posting a question with code demonstrating the problem. Depending on how the static method is called, though, you can do that with `this.name` (since the way static methods are usually called means `this` refers to the constructor function): http://jsfiddle.net/5f1rxme4/ – T.J. Crowder Jan 20 '19 at 09:39
  • @T.J.Crowder Here is the link to my question. https://stackoverflow.com/questions/54529306 There is also a similar question But that is for PHP. https://stackoverflow.com/questions/3391542 – Amarjit Singh Feb 05 '19 at 07:14
1

An instance can get a hold of its constructor function via this.constructor. The name of the function is available as the property .name. So, it's surprisingly straight forward:

console.log(this.constructor.name)
deceze
  • 510,633
  • 85
  • 743
  • 889
1
this.constructor.name

Should do the trick.