Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to get name of child class in parent class?

Tags:

javascript

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();
}
like image 938
Ryan-Neal Mes Avatar asked Dec 12 '16 09:12

Ryan-Neal Mes


2 Answers

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.

like image 75
T.J. Crowder Avatar answered Oct 22 '22 05:10

T.J. Crowder


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)
like image 43
deceze Avatar answered Oct 22 '22 04:10

deceze