In JavaScript ES6 classes, what is the better approach to call a super on the constructor passing all the arguments to the parent class?
I came up with this model using the spread operator, are there any downsides to this approach?
class Parent {
constructor(a, b, c){
console.log("a:", a);
console.log("b:", b);
console.log("c:", c);
}
}
class Child extends Parent {
constructor(){
super(...arguments);
this.doMyStuff();
}
}
let child = new Child("Param A", "Param B", "Param C")
Let's do that old Pros and Cons thing:
Pros
If you change the number of arguments that Parent
accepts, you don't have to change Child
. You still have to change code using Parent
or Child
if the arguments change affects it, but Child
is automatically updated.
(Very weak.) Brevity.
Cons
Loss of clarity. What are the arguments to Child
? Mitigation: Documentation.
Tools can't prompt you with the names of the Child
arguments if they don't know what they are; if the idiom became widespread, tools might analyze the code and figure it out, but I don't think it's likely. You could mitigate that by declaring the arguments even if you don't use them, but then you lose Pro #1 above.
The arity of Child
(Child.length
) is 0
when in effect it's 3
. Again could be mitigated by declaring the args, but again you lose Pro #1.
Neutral
arguments
, you need to be using strict mode (you're not in that code unless it's in a module). (Because strict mode does away with the link between arguments
and the declared arguments.) But you should be using strict mode anyway. :-)Side note: Bergi made the brilliant observation that you can avoid arguments
by using "rest args" instead:
constructor(...args) {
super(...args);
}
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