In A Js Class What Is The Better Way To Call Super Passing All The Arguments Up To The Parent Class?
Solution 1:
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 changeChild
. You still have to change code usingParent
orChild
if the arguments change affects it, butChild
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
) is0
when in effect it's3
. Again could be mitigated by declaring the args, but again you lose Pro #1.
Neutral
- 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 betweenarguments
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);
}
Solution 2:
You could combine destructuring with default params. I'm currently doing it like that:
classParent {
constructor(args = {}){
//destructure what you need herelet {
a = "default a",
b = "default b",
c = "default c"
} = args
this.a = a
this.b = b
this.c = c
}
}
classChildextendsParent {
constructor(args = {}){
//pass args objectsuper(args)
//destructure what you need herelet {
d = "default d",
e = "default e"
} = args
this.d = d
this.e = e
}
}
let parent = newParent({
a: "Param A",
b: "Param B",
c: "Param C"
})
let child = newChild({
a: "Param A",
e: "Param E",
c: "Param C"
})
console.log(parent)
console.log(child)
This way changes your object declaration a bit, since you allways passing variables as a single args object.
You may consider checking for type object though since it wont throw an error if you'll pass something else - instead it would just use default values. But i feel that should count as exprected behaivior.
In the same manner args = {}
handles the no arguments case, but it's not striclty neccessary either, but a good habbit, if you'll for example accidently pull something from args later in non destructuring manner.
Here's a bin: JSBin
Solution 3:
What do you win with the generic approach?
classChildextendsParent {
constructor(a,b,c){
super(a,b,c);
this.doMyStuff();
}
}
is no longer as your version but explicit in what it is expecting and passing on, and therefore easier to understand for the casual reader of your source code.
Post a Comment for "In A Js Class What Is The Better Way To Call Super Passing All The Arguments Up To The Parent Class?"