I have been coding in React js. I have read that in ES6 classes to access 'this' we need to first call super(props) and I would like to know why this is.Answers I have found mainly talk about Javascript being unable to know what 'this' is unless superclass is called. I would like to know what that means because outside the constructor, 'this' is recognized and we don't call super(props) each time.
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = { /* initial state */ };
}
}
“this()” and “super()” cannot be used inside the same constructor, as both cannot be executed at once (both cannot be the first statement). “this” can be passed as an argument in the method and constructor calls.
The super() function is used to give access to methods and properties of a parent or sibling class. The super() function returns an object that represents the parent class.
Use of super() to access superclass constructor As we know, when an object of a class is created, its default constructor is automatically called. To explicitly call the superclass constructor from the subclass constructor, we use super() .
If we call "super()" without any superclass Actually, nothing will be displayed. Since the class named Object is the superclass of all classes in Java. If you call "super()" without any superclass, Internally, the default constructor of the Object class will be invoked (which displays nothing).
This is really complicated, unfortunately.
The short story: access of this
in a subclass before super()
call is not allowed, because in ES6 this
is being born in the base class, therefore super()
is needed to initialize it.
For more information, refer to 15.6.2 Allocating and initializing instances1. The author is one of the few people that explains this in detail.
Here is a relevant sample from the book1 above.
Under the hood, it roughly looks as follows.
// Base class: this is where the instance is allocated
function Person(name) {
// Performed before entering this constructor:
this = Object.create(new.target.prototype);
this.name = name;
}
···
function Employee(name, title) {
// Performed before entering this constructor:
this = uninitialized;
this = Reflect.construct(Person, [name], new.target); // (A)
// super(name);
this.title = title;
}
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