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.
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)?
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.
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.
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 .
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With