~文法メモ~ クラスの基本

クラスの骨格

ECMAScript6ではよく見られる「class」を使って、クラスを定義出来るようになりました。
コンストラクターは、そのまま「constructor」というメソッド名です。 public/protected/privateといったアクセス修飾子はありません。

class MyWindow {
    constructor(x, y, w, h) {
        this.title = "僕のウィンドウ",
        this.x = x
        this.y = y
        this.w = w
        this.h = h
    }
    show() {
        return `タイトル:${this.title}, x:${this.x}, y:${this.y}, w:${this.w}, h:${this.h}`;
    }
}
let win = new MyWindow(10, 20, 500, 300);
hm.debuginfo(win.show());

匿名クラス

関数同様に、クラスも匿名クラスが利用可能です。
これにより「変数に代入」したり、「クラス定義そのものを返す関数」の定義なども可能です。

let MyWindow = class {
    constructor(x, y, w, h) {
        this.title = "僕のウィンドウ",
        this.x = x
        this.y = y
        this.w = w
        this.h = h
    }
    show() {
        return `タイトル:${this.title}, x:${this.x}, y:${this.y}, w:${this.w}, h:${this.h}`;
    }
}
let win = new MyWindow(10, 20, 500, 300);
hm.debuginfo(win.show());
function GetMyWindowClassType() {
    let T = class {
        constructor(x, y, w, h) {
            this.title = "僕のウィンドウ",
            this.x = x
            this.y = y
            this.w = w
            this.h = h
        }
        show() {
            return `タイトル:${this.title}, x:${this.x}, y:${this.y}, w:${this.w}, h:${this.h}`;
        }
    }
    return T;
}

let MyClass = GetMyWindowClassType();
hm.debuginfo(new MyClass(10,20,500,300).show());