Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 class super() with variadic arguments

In ES6, is there a way to call a parent constructor passing through variadic arguments, a la foo.apply(this, arguments)? I've looked for an answer, and the only instances I see are either calling super() (no arguments) or calling super(x, y) (with specific arguments). super.apply(this, arguments) doesn't appear to work.

like image 422
Turner Hayes Avatar asked Jul 18 '16 22:07

Turner Hayes


People also ask

How do you forward an argument to a super class constructor?

In AS2, you can pass parameters to a super class's constructor using super() . This is handy, but what if your constructor accepts an undefined number of parameters, and you want to pass them all to your super constructor (think of the Array class, for instance)?

Why do we need super () in an extended class?

The super keyword is used to call the constructor of its parent class to access the parent's properties and methods. Tip: To understand the "inheritance" concept (parent and child classes) better, read our JavaScript Classes Tutorial.

What does super () do in JS?

The super keyword in JavaScript acts as a reference variable to the parent class. It is mainly used when we want to access a variable, method, or constructor in the base class from the derived class.

What is Subclassing in JavaScript?

Subclassing is a term that refers to inheriting properties for a new object from a base or superclass object. In traditional object-oriented programming, a class B is able to extend another class A . Here we consider A a superclass and B a subclass of A . As such, all instances of B inherit the methods from A .


1 Answers

The pattern I find convenient and follow is

constructor(...args) {
    super(...args);
}

In case you have and use named arguments you could do this instead:

constructor(a, b, c) {
    super(...arguments);
}

References:

  • https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Spread_operator
  • https://kangax.github.io/compat-table/es6/
like image 138
zerkms Avatar answered Oct 26 '22 00:10

zerkms