Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In a js class what is the better way to call super passing all the arguments up to the parent class?

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")
like image 859
cassiozen Avatar asked Sep 26 '22 23:09

cassiozen


1 Answers

Let's do that old Pros and Cons thing:

Pros

  1. 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.

  2. (Very weak.) Brevity.

Cons

  1. Loss of clarity. What are the arguments to Child? Mitigation: Documentation.

  2. 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.

  3. 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

  1. To avoid potential performance issues with 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);
}
like image 105
T.J. Crowder Avatar answered Oct 01 '22 00:10

T.J. Crowder