クラスについて
継承
abstract class Horse { private jockey: string; constructor(private jockey: string) { } run() { console.log(`${this.getName()}が${this.jockey}を乗せて走る`); } abstract getName(): string; } class MihonoBourbon extends Horse { constructor(jockey: string) { super(jockey); } run() { console.log("めっちゃ逃げる"); super.run(); } getName(): string { return "ミホノブルボン"; } } class NaritaTaishin extends Horse { constructor(jockey: string) { super(jockey); } run() { console.log("めっちゃ追い込む"); super.run(); } getName(): string { return "ナリタタイシン"; } } const horse1 = new MihonoBourbon("小島貞博"); const horse2 = new NaritaTaishin("武豊"); horse1.run(); horse2.run();
引数プロパティ
プロパティの宣言と代入を同時にできる
class Horse { private jockey: string; constructor(jockey: string) { this.jockey = jockey; } } ↓ class Horse { constructor(private jockey: string) { } }
Getter&Setter
class Book { private _title: string; get title() { return this._title; } set title(title: string) { this._title = `[${title}]`; } } const b = new Book(); b.title = "真夜中は別の顔"; console.log(b.title);