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();
}
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 instancenew.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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With