所以我想拥有一个不可变的Vector类。为此,我需要为x和y坐标以及一个私有setter设置一个公共getter,以便我可以在构造函数中实际初始化这些值。Typescript private setter public getter convention
我有几个选择在我的处置,所以我想知道哪一个是每个公约。
我能做到这一点是这样的:
class Vector {
constructor(private _x: number, private _y: number) { }
public get x() {
return this._x;
}
public get y() {
return this._y;
}
}
但我不知道是否使用下划线是做一个普通的事情。这可能是一个问题,因为该名称将在智能感知中可见。
第二个选项可能是
class Vector {
constructor(private x: number, private y: number) { }
public get X() {
return this.x;
}
public get Y() {
return this.y;
}
}
据我所知,只有上课的时间与JS首都所以这也可能是一个坏主意。
处理这个问题的首选方法是什么?
可能希望将'number'类型添加到'x'和'y'属性声明中。 – WiredPrairie
没有必要 - 类型推断的真棒力量知道他们已经是数字了。 – Fenton
嗯..我也这么认为,但游乐场没有正确推断它们(我认为编译器也没有)。 – WiredPrairie