Rikard Rikard - 2 years ago 59
Javascript Question

How to know if class constructor was called via super?

If I have this:

class Human {
constructor(){

}
}

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


Is it possible to know if the Human's constructor was called via the
Person
class? I thought about
arguments.callee
but that is deprecated.

Answer Source

It's easy (but ill-advised) to check whether the instance is of a particular subclasss:

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

To check whether it's an instance of the base class (and not a subclass) you can use:

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

[ so long as you haven't messed with the class and overwritten the prototype object ]

You can also check the value of this.constructor.name - it'll reflect the type of the initial constructor called, and doesn't change when the base class constructor is called, although this could fail if the code is minified.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download