Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't this allowed before super()

Tags:

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 */ };
  }
}
like image 729
user4790067 Avatar asked Apr 21 '17 09:04

user4790067


People also ask

Can super and this be written inside same method?

“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.

What is the super () method used for?

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.

Is super () called automatically?

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() .

What happens when you don't use super () constructor?

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).


1 Answers

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;
}
like image 121
Lyubomir Avatar answered Nov 10 '22 08:11

Lyubomir