What is the reason for using "super()" before creating daughter class variables?

Asked

Viewed 56 times

3

I found this question which speaks almost of the same subject but her focus is on access to parent class methods. And my doubt is to know why the use of super() before the declaration of variables in the child class, as in the example below:

class List{

 constructor(){
   this.data = [];
 }

 add(data){
  this.data.push(data);
 }
 showdata(){
   console.log(this.data);
 }
}
class TodoList extends List{

   constructor(){

      //qual a finalidade deste super para a criação de variáveis na classe filha ?
      super(); 
      this.owner = "John";
   }

  showmeowner(){

    console.log(this.owner);

  }

}

const MyList = new TodoList();



If I withdraw the super() of the class builder TodoList the browser returns me the following error:

Uncaught Typeerror: Cannot set Property 'Owner' of Undefined at new Todolist (Bundle.js:54) at Bundle.js:68

Like property owner may be like undefinedif she’s in the class builder TodoList? Because the super()is needed in this situation ?

1 answer

0

In short, technically:

  1. When a regular function is executed with new, she creates a object empty and assigns it to this.
  2. But when a derivative constructor (Inherited) runs, it does not does it. He expects the father builder to do this job.

In other words it is a specification of the language.

Log in to this site: https://javascript.info/class-inheritance and look for this title: 'Overriding constructor'. It is more detailed and technical. If you want it is a great site to learn modern javascript.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.