はじめに
TypeScriptのクラスと継承のサンプルを投稿します。
派生クラスはスーパーコールを行います。
サンプルはシンプルという名称の単純なサンプルです。
クラス、サブクラス、継承、スーパーコール、オブジェクト指向でよく見かけるキーワードです。
恐れることはなにもないです。
この世界を構成するすべてのオブジェクトもまたクラス、サブクラス、継承から誕生していることに気が付くと世界感が変わります。
オブジェクト指向の考え方を身に付けると、「これはあれの派生クラスか」みたいな会話をするようになるかも。
前提
- Visual Studio Codeがインストール済み
- Node.js/npmがインストール済み
- gitからSampleをダウンロードして任意のディレクトリに解凍済み
- OSはWindows7/10を想定
サンプル simple
派生クラスのスーパーコールサンプル。
ファイル構成
| パス | ファイル名 | 説明 | 
|---|---|---|
| . | animals.js | animals.tsのコンパイルにて作成されたJavaScriptファイル | 
| . | animals.js.map | animals.tsのコンパイルにて作成されたmapファイル | 
| . | animals.ts | 動物クラスと継承クラスのTypeScriptファイル | 
| . | README.md | このサンプルの説明と使用方法 | 
| . | tsconfig.json | TypeScriptのコンパイルコンフィグファイル | 
クラス図
へびクラスもうまクラスも動物クラスから植物と動物の違いである「移動(move)」を継承していることをクラス図は物語っています。
プログラムでは、動物クラスのmove()をスーパーコールーします。
実行
cd .animals
tsc --sourcemap animals.ts
node animals.js
結果
へび(Python)のサーミーはスライディングで5m移動
うま(Palomino)のトミーはギャロップで45m移動
コード
animals.ts
class Animal {
    constructor(public name) { }
    move(meters) {
        console.log(this.name + " moved " + meters + "m.");
    }
}
class Snake extends Animal {
    move() {
        console.log("Slithering...");
        super.move(5);
    }
}
class Horse extends Animal {
    move() {
        console.log("Galloping...");
        super.move(45);
    }
}
var sam = new Snake("Sammy the Python")
var tom: Animal = new Horse("Tommy the Palomino")
sam.move()
tom.move(34)
- 動物クラスのコンストラクターで名前を引数で受け取る
- へびクラスのmove()メッソドは動物クラスのmove()メッソドを引数5でスーパーコール
- うまクラスのmove()メッソドは動物クラスのmove()メッソドを引数45でスーパーコール
- tom.move(34)と34を引数で指定するも、うまクラスのmove()は引数を指定していないので出力に反映しない
ポイント
派生クラスは親となるクラスを extends と super でそっくり自己のメッソドとして使用可能となります。
ノート
神になった気分で「人間クラス(Human)」を追加してみました。
ちゃんと移動距離を引数定義しました。
改修ソース
class Animal {
    constructor(public name) { }
    move(meters) {
        console.log(this.name + " moved " + meters + "m.");
    }
}
class Snake extends Animal {
    move() {
        console.log("Slithering...");
        super.move(5);
    }
}
class Horse extends Animal {
    move() {
        console.log("Galloping...");
        super.move(45);
    }
}
class Human extends Animal {
    move(meters) {
        console.log("Warlking...");
        super.move(meters);
    }
}
var sam = new Snake("Sammy the Python")
var tom: Animal = new Horse("Tommy the Palomino")
var poo: Animal = new Human("Pooshikin the Mankaind")
sam.move()
tom.move(34)
poo.move(10)
Slithering...
Sammy the Python moved 5m.
Galloping...
Tommy the Palomino moved 45m.
Warlking...
Pooshikin the Mankaind moved 10m.
まとめ
TypeScriptの最大の功績はクラスをコーディングする道を開いたことです。
「求めよ若者よ、道は開かれる」
どしどしクラス作りに励みましょう。
以上、おそまつ

