noobcoderiam
noobcoderiam

Reputation: 508

In JavaScript classes, you need to always call super? Confused about this statement

I'm currently learning react and saw this line during the tutorial:

"In JavaScript classes, you need to always call super when defining the constructor of a subclass."

I thought the only time super() needed to be called was when you wanted to use properties of a parent class, and id you didn't need those properties you didn't have to call super(). I get it would be kind of pointless to create a child class that doesn't use properties from it's parent, but is the above statement true to JS or only to react?

Genuinely confused as a noob to web dev.

Upvotes: 7

Views: 4497

Answers (2)

Estus Flask
Estus Flask

Reputation: 222369

A subclass should always call parent's constructor, this should happen before this is accessed the first time in a subclass. This is deliberate limitation of ES6 classes. Otherwise it wouldn't be a subclass but something else.

The only case when a subclass doesn't need super is when it uses implicit constructor, i.e. it's inherited from a parent:

class Bar extends Foo {}

is a shortcut for

class Bar extends Foo {
  constructor(...args) {
    super(...args);
  }
}

This is common case in React, because explicit constructor is used relatively rare, while class fields are used often and are syntactic sugar for explicit constructor:

class MyComponent extends React.Component {
  state = { foo: this.props.foo };
  ...
}

is a shortcut for

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { foo: this.props.foo };
  }
  ...
}

Upvotes: 6

James-Prescott
James-Prescott

Reputation: 91

You can't have a sub-class that doesn't use all of the parent class properties. That would defeat the point of defining a sub-class at all.

Imagine you have a class Dog and a sub-class Labrador which inherits from Dog. You would give the Dog class properties such as tail and ears. You can't then declare the sub-class Labrador and not give it a tail and ears because then it wouldn't be a dog.

The link Artyom provided shows another example; you can't have a square without a length of the sides.

That's why super() needs to be called in a sub-class. Hope that helps!

Upvotes: 2

Related Questions