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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With