cas*_*zen 5 javascript ecmascript-6
在JavaScript ES6类中,在将所有参数传递给父类的构造函数上调用super的更好方法是什么?
我使用扩展运算符想出了这个模型,这种方法有什么缺点吗?
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")
Run Code Online (Sandbox Code Playgroud)
让我们做旧的利弊:
优点
如果更改Parent
接受的参数数量,则不必更改Child
. 您仍然必须使用 Parent
或Child
参数更改影响它来更改代码,但Child
会自动更新。
(非常弱。)简洁。
缺点
失去清晰度。的论据是Child
什么?缓解措施:文档。
如果工具Child
不知道它们是什么,它们就无法提示您输入参数的名称;如果这个习语变得普遍,工具可能会分析代码并弄清楚,但我认为不太可能。即使您不使用它们,您也可以通过声明参数来缓解这种情况,但是您会失去上面的 Pro #1。
Child
( Child.length
)的元数是0
当它实际上是3
. 再次可以通过声明 args 来缓解,但是你又失去了 Pro #1。
中性的
arguments
,您需要使用严格模式(除非它在模块中,否则您不在该代码中)。(因为严格模式消除了arguments
和声明参数之间的联系。)但无论如何你应该使用严格模式。:-)旁注:Bergi进行了精彩的观察,您可以arguments
通过使用“rest args”来避免:
constructor(...args) {
super(...args);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3535 次 |
最近记录: |