I would like to get the parent class name (Parent
), but I'm only able to retrieve the child class name with this code (Child
)...
'use strict'; class Parent { } class Child extends Parent { } var instance = new Child(); console.log(instance.constructor.name);
Is it possible ?
Thanks !
Use the keyword super within the overridden method in the child class to use the parent class method. You can only use the keyword within the overridden method though.
The parent class can hold reference to both the parent and child objects. If a parent class variable holds reference of the child class, and the value is present in both the classes, in general, the reference belongs to the parent class variable. This is due to the run-time polymorphism characteristic in Java.
A parent class constructor is not inherited in child class and this is why super() is added automatically in child class constructor if there is no explicit call to super or this.
ES6 classes inherit from each other. So when instance.constructor
refers to the Child
, then you can use Object.getPrototypeOf(instance.constructor)
to get the Parent
, and then access .name
:
Object.getPrototypeOf(instance.constructor).name // == "Parent"
Of course, full ES6 compliance and non-minified code are necessary for this to work. You should never rely on function names in code.
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