Can anyone explain the keyword "super ()" in ES6 Javascript (especially regarding React)?

I am learning React.js and I see that the super keyword used constructor functions a lot.

I understand that super allows a subclass to have access to the this . However, I cannot find any more explanation.

  • Why does calling super() magically give my class access to this ?
  • Why does the super keyword bind this to the class context?
  • When I'm not subclassing, why don't I call super() ?
+5
source share
2 answers

Sorry for the pic. in Japanese, but looks easy to understand.

When you use the super function in your class member functions, you are also supposed to use the extends . When you call super as super(args) in the extending class, it calls the extended constructor of the class. You can also call other member functions of the extended class with super.methods(args) rather than super(args) .

extends and super (From https://liginc.co.jp/266587 )

UPDATE

FYI: What is the difference between "super ()" and "super (props)" in React when using es6 classes? This discussion explains well how super in the reaction component affects this context constraint. Good to read.

+5
source

Actually, calling super in the constructor calls the constructor of the parent class. You can have access to this regardless of its use or not, but in the reaction context, these properties related to this , such as this.props and this.state , are set and configured correctly in the constructor of the React.Component class, so that you first called super, so this properly configured.

+2
source

Source: https://habr.com/ru/post/1263650/


All Articles