自动将参数传递给 super()

Automate parameters passing to super()

提问人:Edgar Derby 提问时间:3/10/2023 最后编辑:Peter SeligerEdgar Derby 更新时间:3/15/2023 访问量:86

问:

我有一个父类,例如:

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 个扩展类,我也需要更改这些类。LionAnimal

有没有办法重写此代码,以便将 的所有参数隐式添加到扩展它的类中?Animal

JavaScript TypeScript 继承 参数传递 超级

评论

0赞 InSync 3/10/2023
是你想要的吗?super({...arguments[0]})
0赞 jcalz 3/10/2023
这种方法是否满足您的需求?如果是这样,我可以写一个答案来解释;如果没有,我错过了什么?(请注意,TypeScript 的结构类型意味着额外的属性不会违反类型,因此,如果您出于某种原因需要显式阻止额外的属性,我希望您能在演示该原因的示例中进行编辑
0赞 Edgar Derby 3/10/2023
@jcalz 是的,这实际上很完美。如果你能写一个独立的答案,我会把它标记为正确。:)
0赞 Bergi 3/10/2023
"我可能需要向 Animal 添加一个新参数,现在如果我还有 100 个扩展 Animal 的类,我也需要更改它们。- 嗯,这不是没有道理的。如果要更改构造函数的接口,则还必须更改调用构造函数的每个位置。这是正常的,函数、方法、类构造函数也是如此。你的实际问题是有 100 个类继承自 ,这听起来像是代码味。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',
});