LoginSignup
5

More than 5 years have passed since last update.

JavaScriptのクラスフィールドの話

Posted at

最初に

MobXの勉強してたら、しれっとクラスフィールドが使われていたので、びっくりした。

どこかのバージョンで入るとは聞いていたけど、深追いしていませんでした。

ので、少し調べましたというお話。

20180607現在、ESnextのStage3です。
classfield.png

動作環境

自分の記事ですが、下記を参考にしてください。
https://qiita.com/tsuuuuu_san/items/d27b536fc39cf9fc899c#%E4%BB%98%E9%8C%B2

早速使う

参考:https://github.com/tc39/proposal-class-fields

フィールド宣言

ES2015の場合
class Myself {
    // この辺にクラスフィールド書きたいけど、書けないんだよ

    constructor() {
        // しょうがないので、ここに書くと使えるよ
        this.name = 'tsuuuuu_san';
    }
}

const myself = new Myself();
console.log('name:', myself.name);  // name: tsuuuuu_san
ESnextの提案
class Myself {
    name = 'tsuuuuu_san';
}

const myself = new Myself();
console.log('name:', myself.name);  // name: tsuuuuu_san

プライベートフィールド

フィールドに「#」をつけると、プライベートになる。

class Myself {
    name = 'tsuuuuu_san';
    #age = 16;

    get anserAge() {
        return this.#age;
    }
}

const myself = new Myself();
console.log('name:', myself.name);          // name: tsuuuuu_san
console.log('age:', myself.age);            // age: undefined
console.log('anserAge:', myself.anserAge);  // anserAge: 16

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
5