提问人:Edgar Derby 提问时间:3/10/2023 最后编辑:Peter SeligerEdgar Derby 更新时间:3/15/2023 访问量:86
自动将参数传递给 super()
Automate parameters passing to super()
问:
我有一个父类,例如:
class Animal {
constructor({name, color}) {
// Does something with name and color.
}
}
然后我有很多扩展 Animal 的类。例如:
class Lion extends Animal {
constructor({name, color, tailLength}) {
super({name: name, color: color})
// Does something with tailLength.
}
}
我的问题是这段代码不是很干。例如,我可能需要向 Animal 添加一个新参数:
class Animal {
constructor({name, color, height}) {
// Does something with name, color and height.
}
}
现在我还需要更改界面,如果我还有 100 个扩展类,我也需要更改这些类。Lion
Animal
有没有办法重写此代码,以便将 的所有参数隐式添加到扩展它的类中?Animal
答:
1赞
Peter Seliger
3/10/2023
#1
由于使用单个类似配置的对象作为任何与动物相关的构造函数的唯一参数,因此应使用 rest 参数语法,以便允许通用且可扩展的方法。
class Animal {
constructor({ name, color /* and anything the OP might furtherly want */ }) {
// does currently something with name and color.
}
}
class Lion extends Animal {
constructor({ tailLength, ...configRest }) {
super(configRest)
// does something with tailLength.
}
}
// usage ase e.g.
const lion = new Lion({
name: 'Simba', color: 'yellowish'/*, height*/, tailLength: 'long',
});
评论
super({...arguments[0]})
Animal
的类,我也需要更改它们。- 嗯,这不是没有道理的。如果要更改构造函数的接口,则还必须更改调用构造函数的每个位置。这是正常的,函数、方法、类构造函数也是如此。你的实际问题是有 100 个类继承自 ,这听起来像是代码味。
Animal