我似乎记得看到一个快捷方式,如果属性和构造函数参数被命名为相同的东西,你不必在构造函数中执行 this.foo 赋值 - 但我似乎无法找到它的参考谷歌搜索。
例如:
class Polygon {
constructor(height, width) {
this.height = height;
this.width = width;
}
}
你能不能做类似的事情
class Polygon {
constructor(height=height, width=width) {
// wasn't there a way to declare these arguments so it auto sets the instance variables?
}
}
原文由 MonkeyBonkey 发布,翻译遵循 CC BY-SA 4.0 许可协议
如果您喜欢这种事情,您可能会定义一个执行此操作的超类:
当然,你是否应该这样做是值得商榷的,但这是可能的。请注意,由于可能存在缩小问题,我们不能依赖构造函数中参数名称的名称。