0

In JavaScript ES6, if super() must always be invoked in a subclass constructor before accessing this, why isn't it automatically invoked by the JS engine?

Le me make an example:

class Animal {
  constructor (name) {
    this.name = name;
  }
}

class Dog extends Animal {
  constructor (name, breed) {
    super();
    this.breed = breed;
  }
}

Couldn't it simply be?

class Dog extends Animal {
  constructor (name, breed) {
    this.breed = breed;
  }
}

I mean, I know the second example doesn't work, but why hasn't this feature been built in JS to automate the process? Why do we have to type super() each time? Is there a specific language design constraint that would otherwise break things?

Pensierinmusica
  • 6,404
  • 9
  • 40
  • 58
  • Duplicates came from this google search: [site:stackoverflow.com javascript why must we call super](https://www.google.com/search?q=site%3Astackoverflow.com+javascript+why+must+we+manually+invoke+super) –  Apr 05 '17 at 12:01
  • The Google results of that search do not answer the question at hand. – Pensierinmusica Apr 06 '17 at 14:44
  • Strange, I wonder if I posted a link to a different search. Anyway, I found the duplicates using Google. –  Apr 06 '17 at 14:59
  • 1
    Thanks, I think this might explain it, couldn't find it before: http://stackoverflow.com/questions/41381489/es6-javascript-class-inheritance-why-we-need-call-to-super-from-derived-class – Pensierinmusica Apr 06 '17 at 22:55

1 Answers1

2

That's because the base constructor might contain parameters, in which case you'd have to call super() passing them the way you like.

And beyond that, just thinking of pure OOP, there might be various base constructors available with different signatures that would fall under your control. Automating this process would be unpractical.

Sebas
  • 21,192
  • 9
  • 55
  • 109