2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

javascript class構文でstaticプロパティ

Last updated at Posted at 2018-03-27

#javascript の class構文 確かに便利だが…

class Foo {
    static message : "hello foo!"
}

と書けないですね。

let Foo = Object.assign(class {
    get message () {
        return this.constructor.message === undefined ?
            super.message : this.constructor.message;
    }

    set message (v) {
        this.constructor.message = v;
        return true;
    }
},{message: "hello foo!"})

let Bar = class extends Foo {}

//テスト 出力は hello foo!
console.log(Bar.message);

Bar.message = "hello bar!";// Object.assign(Bar, {message: "hello bar!"})と挙動は同じ
console.log(Foo.message);
console.log(new Foo().message);
console.log(Bar.message);
console.log(new Bar().message);

new Bar().message = undefined;
console.log(Foo.message);
console.log(new Foo().message);
console.log(Bar.message);
console.log(new Bar().message);

// staticかどうかチェック
new Foo().message = "bye foo!";
console.log(Foo.message);
console.log(new Foo().message);

Foo.message = undefined;
console.log(Foo.message);
console.log(Bar.message);

と書くことで、staticなプロパティになります。 参考までにどうぞ。

2
1
5

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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?