javascript - Defining a Class in ES2015, what is the constructor method and why is it essential? -


i in process of learning es2015 , i'm not understanding classes. understanding define class this:

class parent {   constructor() {     // ...   } } 

and subclass this: (where super() must invoked run constructor parent class).

class subclass extends parent {   constructor(name, description, url) {     // subclass must call super invoke parent's constructor method     super();   } } 

what constructor method, why important, , why parents constructor needs invoked when creating instance of subclass?

when create new instance of class, constructor method called arguments passed through. in function, put code construct instance of class, initializing properties.

class person{   constructor(name){     this.name = name;   }   sayhi(){     alert(`${this.name} says hello!`);   } }  let person = new person('jerry');//this param send constructor method person.sayhi(); 

the result of code alert saying "jerry says hello!".
although, constructor method not required. following code work too.

class person{   sayhi(){     alert("someone says hello!");   } } let person = new person(); person.sayhi(); 

in case have subclass, might want call constructor method of parent class. not required, in cases done.

class person{   constructor(name){     this.name = name;   }   sayhi(){     alert(`${this.name} says hello!`);   } }  class sophisticatedperson extends person{   constructor(name){     super(name);//this call constructor method of person class   }   sayhi(){     alert(`${this.name} says: top of hat you, sir!`);   }   oldsayhi(){     super.sayhi();//call sayhi of person class   } }  let person = new sophisticatedperson('jerry'); person.sayhi();//calls overidden sayhi method of sophisticatedperson class person.oldsayhi();//calls oldsayhi of sophisticatedperson class calls sayhi of person class 

with 'super' can call constructor via 'super()' or other methods via 'super.methodname()' of parent class illustrated above.

extra notice: if don't provide constructor method on child class, parent constructor method called.


Comments

Popular posts from this blog

java - Run spring boot application error: Cannot instantiate interface org.springframework.context.ApplicationListener -

reactjs - React router and this.props.children - how to pass state to this.props.children -

python - pip wont install .WHL files -