LoginSignup
0

More than 5 years have passed since last update.

TypeScript Sampleをやってみるその9

Last updated at Posted at 2018-06-07

はじめに

TypeScriptのクラス継承のサンプルを投稿します。
派生クラスはスーパーコールを行います。
サンプルはシンプルという名称の単純なサンプルです。
クラス、サブクラス、継承、スーパーコール、オブジェクト指向でよく見かけるキーワードです。
恐れることはなにもないです。
この世界を構成するすべてのオブジェクトもまたクラス、サブクラス、継承から誕生していることに気が付くと世界感が変わります。
オブジェクト指向の考え方を身に付けると、「これはあれの派生クラスか」みたいな会話をするようになるかも。

前提

サンプル simple

派生クラスのスーパーコールサンプル。

ファイル構成

パス ファイル名 説明
. animals.js animals.tsのコンパイルにて作成されたJavaScriptファイル
. animals.js.map animals.tsのコンパイルにて作成されたmapファイル
. animals.ts 動物クラスと継承クラスのTypeScriptファイル
. README.md このサンプルの説明と使用方法
. tsconfig.json TypeScriptのコンパイルコンフィグファイル

クラス図

TS_045.jpg

へびクラスもうまクラスも動物クラスから植物と動物の違いである「移動(move)」を継承していることをクラス図は物語っています。
プログラムでは、動物クラスのmove()をスーパーコールーします。

実行

cd .animals
tsc --sourcemap animals.ts
node animals.js

結果

TS_046.jpg

へび(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()は引数を指定していないので出力に反映しない

ポイント

派生クラスは親となるクラスを extendssuper でそっくり自己のメッソドとして使用可能となります。

ノート

神になった気分で「人間クラス(Human)」を追加してみました。
ちゃんと移動距離を引数定義しました。

改修ソース

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);
    }
}

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の最大の功績はクラスをコーディングする道を開いたことです。
「求めよ若者よ、道は開かれる」
どしどしクラス作りに励みましょう。

以上、おそまつ

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0