Ondra Žižka Ondra Žižka - 1 year ago 170
TypeScript Question

TypeScript / JavaScript - How to get superclass of a class?

Let's say I have:

class Foo {}
class Bar extends Foo {}
var clazz = Bar;

I figured out that to get

How can I find out what is the parent class of

Answer Source

As commented on the answer by @MattiasBuelens, it should be: obj.constructor and not obj.prototype.constructor as obj.prototype is null (the prototype property exists on the class Bar but not the instances).

As for getting the constructor of Foo, well this is an ugly hack:

let FooCtor = Object.getPrototypeOf(Object.getPrototypeOf(obj)).constructor;
var foo = new FooCtor();


If you want to do the same thing but with the Bar class instead of instance of it, then:

let FooCtor = Object.getPrototypeOf(Bar.prototype).constructor;
var foo = new FooCtor();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download