在js类中,调用super将所有参数传递给父类的更好的方法是什么? [英] In a js class what is the better way to call super passing all the arguments up to the parent class?
问题描述
在JavaScript ES6类中,在将所有参数传递给父类的构造函数上调用super的更好方法是什么?
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:
专业人士
-
如果更改
Parent
接受的参数数量,则不必更改Child
.如果参数更改影响了代码,您仍然必须使用Parent
或Child
更改代码,但是Child
会自动更新.
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.
(非常弱.)简短.
缺点
-
缺乏清晰度.
Child
的参数是什么?缓解措施:文档.
Loss of clarity. What are the arguments to
Child
? Mitigation: Documentation.
如果工具不知道它们是什么,则无法使用 Child
参数的名称提示您.如果这个习惯用法变得很普遍,工具可能会分析代码并找出答案,但我认为这不太可能.您可以通过声明参数来缓解这种情况,即使您不使用它们也是如此,但是您会丢失上面的Pro#1.
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.
Child
( Child.length
)的平均值为 0
,而实际上为 3
.再次声明args可以缓解问题,但是您又失去了Pro#1.
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.
中性
- 为避免使用
arguments
引起潜在的性能问题,您需要使用严格模式(除非位于模块中,否则您将不在该代码中).(因为严格模式取消了arguments
和声明的参数之间的链接.)但是无论如何,您都应该使用严格模式.:-)
- 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. :-)
旁注: Bergi 将 arguments :
Side note: Bergi made the brilliant observation that you can avoid arguments
by using "rest args" instead:
constructor(...args) {
super(...args);
}
这篇关于在js类中,调用super将所有参数传递给父类的更好的方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!