Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why am I getting compile error in JavaScript when extending a class with a default constructor?

I’m trying to create a subclass in JavaScript and am encountering an error related to the use of this in the subclass constructor. Here’s the code I’m working with:

class Mammals {
  // No constructor defined explicitly
}

class Humans extends Mammals {
  constructor(name) {
    this.name = name;
  }
}

const jimmy = new Humans("Jimmy");
console.log(jimmy.name);

I understand that if a base class has a default no-argument constructor, JavaScript should allow the subclass constructor to run without explicitly calling super(). I thought that since Mammals has a default constructor (as it’s not explicitly defined), the Humans constructor should not need to call super().

However, I am still encountering the error message:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Must call super constructor in derived class before accessing ‘this’
or returning from derived constructor

Can someone explain why

Thank you for your help!

>Solution :

Where did you get the idea that if a base class has no constructor, JavaScript should allow the subclass constructor to run without explicitly calling super()?

JavaScript requires calling super() before you can access this so suppose if you never access this then yea, you don’t need to call super but otherwise you do.

As for why, because unless the class you’re deriving from has a chance to call its constructor, that part of the class doesn’t exist.

Let’s say you did this

class Mammals {
  // No constructor defined explicitly
  weight = 3;
}

Now in Humans constructor, you should be able to access this.weight but you can’t if you haven’t called super() (a) because of the rule above but (b) because you can’t access something that hasn’t been constructed and Animals has not been constructed until you call super()

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading