JSクラスとTS静的キーワードの簡単な考察

1763 ワード

最近インフラリーダーの方瑶さんのTS講座を聞いて、思い出して、簡単に整理しました.
以前ES 6のクラス構文を使用した場合、既存のjavaで使用されている静的メソッドと静的変数を使用したいと思っていましたが、あまり覚えていません.
この問題を解決するために、私は突然1つの考えを思いつきました.それはTSで符号化とコンパイルを行い、生成されたコードを見てみましょう.
まず,TSには当然静的方法と静的変数があるので,それらを用いてコードを記述する.
class Dog {
    public name: string;
    private age: number;
    public static numTail: number;

    constructor(name, age) {
        this.name = name;
        this.age = age;
        Dog.numTail = 1;
    }

    hi(): void {
      console.log(`Hello I am ${this.name} and I am ${this.age} years old`);  
    }

    static wow(): void {
        console.log(`We are Dogs and We have ${Dog.numTail} tail(s)!`);
    }
}

function foo(d: Dog) : void {
    d.hi();
}

const d1 = new Dog('Nabi', 3);
const d2 = new Dog('Zelda', 10);

foo(d1);
d2.hi();
Dog.wow();
コンパイルして実行します.
$ tsc example.ts
$ node examle.js
Hello I am Nabi and I am 3 years old
Hello I am Zelda and I am 10 years old
We are Dogs and We have 1 tail(s)!  
よかった.では最後に変換後のコードを確認します.
var Dog = (function () {
    function Dog(name, age) {
        this.name = name;
        this.age = age;
        Dog.numTail = 1;
    }
    Dog.prototype.hi = function () {
        console.log("Hello I am " + this.name + " and I am " + this.age + " years old");
    };
    Dog.wow = function () {
        console.log("We are Dogs and We have " + Dog.numTail + " tail(s)!");
    };
    return Dog;
})();
function foo(d) {
    d.hi();
}
var d1 = new Dog('Nabi', 3);
var d2 = new Dog('Zelda', 10);
foo(d1);
d2.hi();
Dog.wow();
これは当然の結果であるが,プロトタイプと構造関数を用いてクラスを生成することを決定できる.JSの知識+0.1.