jsのクラスってコンストラクタに全部書いた方がよくね?
jsのクラスはこんな感じで書きます
class Position { constructor(x, y) { this.x = x; this.y = y; } getX() { return this.x; } getY() { return this.y; } getDistance() { return Math.sqrt(this.x * this.x + this.y * this.y); } }
この書き方の辛いところ
- フィールドをprivateにできないからxとyが外から丸見え。セッター呼び放題
- フィールドが増えるたびに
this.v = v;
をコンストラクタに書く必要がある
それならこっちの方がよくね?
class Position { constructor(x, y) { this.getX = () => x; this.getY = () => y; this.getDistance = () => Math.sqrt(x * x + y * y); } }
辛いところは全部解消されてる
しかもコンストラクタ引数をconstな変数に入れたらimmutableにもできる
class ImmutablePosition { constructor(_x, _y) { const x = _x, y = _y; this.getX = () => x; this.getY = () => y; this.getDistance = () => Math.sqrt(x * x + y * y); } }
どや