Search code examples
javascriptclasssuper

In javascript class, how do I super() all the existing arguments?


Hypothetically, if a parent class has so many arguments in the class to be inherited, how do I super() all the existing arguments in the parent elements to its extended class?

Should I figure out all the arguments in the constructor of the parent class and manually type them all?

I tried to google it like 'super all, super everything, super all the existing ..etc' but still couldn't find a answer.

Thank you in advance.


Solution

  • If the child and parent take the same arguments, use rest and spread:

    class Child extends Parent {
      constructor(...args) {
        super(...args);
      }
    }
    

    If the constructor signatures are the same, this will work for any Child regardless of what Parent's arguments are. This also works for multiple inherited classes, eg:

    class GrandChild extends Child {
      constructor(...args) {
        super(...args);
      }
    }
    

    But long inheritance chains are usually an antipattern in JS. I'd recommend avoiding them in most cases, unless there's a really good reason for it.

    If the child has an extra trailing argument, passing it to the parent if the parent doesn't define such an argument will work just fine.

    If the child has an extra leading argument, use:

    class Child extends Parent {
      constructor(childArg, ...args) {
        super(...args);
      }
    }