Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Introduction to the function of super in JavaScript

2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

The main content of this article is "introduction to the function of super in JavaScript". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "introduction to the function of super in JavaScript".

First of all, I can't remember the super (props) I wrote in my career:

Class Checkbox extends React.Component {constructor (props) {super (props); this.state = {isOn: true};} / /.}

Of course, in the Class Field proposal (class fields proposal), it is suggested that we skip the beginning:

Class Checkbox extends React.Component {state = {isOn: true}; / /...}

This syntax was intended to be used when React 0.13 added support for normal classes in 2015. Defining constructor and calling super (props) is always a temporary solution, perhaps until class fields provide an alternative that is not so anti-human in engineering.

But let's go back to the previous example, this time using only the features of ES2015:

Class Checkbox extends React.Component {constructor (props) {super (props); this.state = {isOn: true};} / /.}

Why are we calling super? Can I call it? What happens if you don't pass the prop parameter if you have to call it? Are there any other parameters? Let's give it a try:

In JavaScript, super refers to the constructor of the parent class. (in our example, it points to the implementation of React.Component. )

It is important that you cannot use this in the constructor before calling the parent constructor. JavaScript won't let you do this:

Class Checkbox extends React.Component {constructor (props) {/ / you can't use `this` super (props) here; / / now you can use this.state = {isOn: true};} / /.}

There is a good reason why JavaScript enforces the parent constructor before using this. Let's first look at the structure of the following class:

Class Person {constructor (name) {this.name = name;}} class PolitePerson extends Person {constructor (name) {this.greetColleagues (); / / this line of code is invalid. I'll tell you why super (name);} greetColleagues () {alert ('Good morning folksgiving');}}

If you are allowed to use this before calling super. After a while, we may modify the greetColleagues and add the name of Person to the prompt:

GreetColleagues () {alert ('Good morning portfolio'); alert ('My name is'+ this.name +', nice to meet youthful');}

But we forgot that super () called this.greetColleagues () before setting up this.name. So this.name is not defined yet! As you can see, it's hard for code like this to figure out what the problem is.

To avoid such traps, JavaScript forces that if you want to use this in your constructor, you must first call super. Let the parents do their own thing first! This limitation also applies to React components that are defined as classes:

Constructor (props) {super (props); / / here you can use `this` this.state = {isOn: true};}

This leaves us with another question: why pass the props parameter?

You might think that it is necessary to pass props to super, which enables the constructor of React.Component to initialize this.props:

/ / Inside Reactclass Component {constructor (props) {this.props = props; / /...}}

This is very close to the correct answer-in fact, that's what it does.

But for some reason, even if you don't pass the props parameter when you call super, you can still access this.props in render and other methods. If you don't believe me, you can try it yourself! )

Why on earth is this? It turns out that React also allocates props on the instance after calling the constructor:

/ / Inside React const instance = new YourComponent (props); instance.props = props

So even if you forget to pass props to super (), React will still set them later. There's a reason for that.

When React adds support for classes, it doesn't just add support for ES6 classes. Its goal is to support class abstraction as widely as possible. It is not clear how ClojureScript, CoffeeScript, ES6, Fable, Scala.js, TypeScript, or other solutions have been relatively successful in defining components. So React deliberately doesn't care if you need to call super ()-- even if it's the ES6 class.

So does that mean you can write super () instead of super (props)?

Probably not, because it's still confusing. Of course, React allocates this.props later after your constructor runs, but this.props remains undefined in the interval after calling super () and before the end of the constructor:

/ / Inside Reactclass Component {constructor (props) {this.props = props; / /...}} / / Inside your codeclass Button extends React.Component {constructor (props) {super (); / / We forgot to pass the props parameter console.log (props); / / {} console.log (this.props); / / undefined} / /.}

If this happens in a method called from the constructor, it can cause a lot of trouble for debugging. This is why I recommend always calling super (props), even if it is not necessary:

Class Button extends React.Component {constructor (props) {super (props); / / passed the props parameter console.log (props); / / {} console.log (this.props); / / {}} / /.}

This ensures that the this.props can be set before the constructor exits.

The last point is that React users have long been curious.

You may have noticed that when you use Context API in a class (whether it's the old contextTypes or the new contextType API added in React 16.6), context is passed to the constructor as the second argument.

So why don't we write super (props, context)? We can do this, but the frequency of using context is low, so the pit doesn't have that much impact.

According to the description of the class field proposal, most of these pits will disappear. If there is no explicit constructor, all parameters are passed automatically. This allows you to include a reference to this.props or this.context in an expression such as state = {}, if necessary.

With Hooks, we don't even have super or this anymore. But this is another topic.

At this point, I believe you have a deeper understanding of the "introduction to the functions of super in JavaScript". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report