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.