Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 821
Rikard Avatar asked May 15 '16 18:05

Rikard


People also ask

Is super class constructor automatically called?

With super(parameter list) , the superclass constructor with a matching parameter list is called. Note: If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass.

How this () and super () are used with constructors?

The this() constructor refers to the current class object. The super() constructor refers immediate parent class object. It is used for invoking the current class method. It is used for invoking parent class methods.

When super () is called?

Super is called when we want to inherit some of the parameters from the parent class. It is not compulsory as the compiler always call the default constructor. If you want to inherit a constructor having some parameters then you need to call the super.

What does super () __ Init__ do?

Understanding Python super() with __init__() methods It is known as a constructor in Object-Oriented terminology. This method when called, allows the class to initialize the attributes of the class. The super() function allows us to avoid using the base class name explicitly.


1 Answers

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.

like image 122
Alnitak Avatar answered Oct 07 '22 23:10

Alnitak