0

I'm getting warnings in Visual Studio Code when I'm using a constructor with a different arguments. Do the arguments in extended classes need to be the same as the super class?

Class:

class Options {
  constructor(name = null) {
     this.name = name;
  }
}

class ExtendedClass extends Options {
  constructor(colors = null, option = false) {
    if (colors!=null) {
      this.numberOfColors = colors;
    }
    this.option = option;
  }
}

UPDATE:
It looks like using different arguments doesn't matter but that the issue is that a call to super is the problem? Need to test more but it looks like this is the issue:

class ExtendedClass extends Options {
  constructor(colors = null, option = false) {
    super();

    if (colors!=null) {
      this.numberOfColors = colors;
    }
    this.option = option;
  }
}
3
  • Ok. I don't get any warning, though. Commented Apr 29, 2020 at 18:49
  • 2
    Yes, you can use a different signature, but I would urge you not to do. Treat a constructor like any other method in that regard - you can add optional parameters, but you should not change the meaning of existing parameters. Commented Apr 29, 2020 at 18:56
  • 1
    Also worth noting that the warning makes a lot of sense. You are declaring that you extend Options, and Options has a constructor that does something. So it should make logical sense that anything that is an Option (by inheritance) needs to run that constructor logic before it is ready for use. And the super call isn't automatic because you might not always want it at the start of your constructor (perhaps if you start with some error handling), so you must manually add that call to make sure that logic is run, else your Option child class isn't fully initialized. Commented Apr 29, 2020 at 19:03

1 Answer 1

1

Do the arguments in extended classes [constructors] need to be the same as the super class [constructor]?

Short answer: no.

However, super() expects the same arguments as the super class constructor. (super() calls the super class constructor with the supplied arguments.)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.