How to find out if the class constructor is called via super?

If I have this:

class Human {
    constructor(){

    }
}

class Person extends Human {
    constructor(){
        super();
    }
}

Can I find out if the Human constructor is called through a class Person? I thought about arguments.callee, but it's out of date.

+4
source share
1 answer

It is easy (but not recommended) to check if an instance is specific subclasses:

class Human {
    constructor(){
        console.log(this instanceof Person);
    }
}

To check if this is an instance of a base class (and not a subclass), you can use:

Object.getPrototypeOf(this) === Human.prototype

[until you mess up with the class and rewrite the object prototype]

this.constructor.name - - , , .

+4

All Articles