Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can someone explain the 'super()' keyword in ES6 Javascript (especially related to React)?

I'm learning React.js, and I see the super keyword used a lot in constructor functions.

I understand that super allows a subclass to have access to the this keyword. However, I can't find much more explanation.

  • Why does calling super(), magically give my class access to this?
  • Why does the super keyword bind this to the context of the class?
  • When I'm not dealing with a subclass, why don't I have to call super()?
like image 687
thatDubstepSound Avatar asked Feb 01 '17 01:02

thatDubstepSound


2 Answers

Actually, a super call in the constructor calls the constructor of the parent class. You can have access to this independently of using it or not, but in the context of react, this properties associated with this, like this.props and this.state are set and configured properly in the React.Component class constructor. So that's why you must call super first, so that this is properly setup.

like image 101
Luan Nico Avatar answered Oct 19 '22 06:10

Luan Nico


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

When you use super function in your class member functions, extends keyword is also expected to be used. When you call super like super(args) in the extending class, it calls the constructor of the extended class. You can also call the other member functions of the extended class with super.methods(args), not super(args).

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

UPDATE

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

like image 7
IzumiSy Avatar answered Oct 19 '22 04:10

IzumiSy