Search code examples
javascriptreflectiontypescriptsuperclassintrospection

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 Bar there's clazz.prototype.constructor.

How can I find out what is the parent class of Bar?


Solution

  • 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();
    

    Edit

    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();