Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get parent class name from child with ES6?

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 !

like image 761
Swadon Avatar asked Jul 27 '15 03:07

Swadon


People also ask

How do you access parent method from child class?

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.

Can we create the reference of parent class with child class?

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.

Does child class inherit parent constructor?

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.


1 Answers

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.

like image 125
Bergi Avatar answered Sep 22 '22 15:09

Bergi