LoginSignup
0
0

More than 5 years have passed since last update.

es6でclassの定数を扱う。インスタンスメソッドからclassの定数を参照する

Last updated at Posted at 2019-05-09

結論から書く

  • インスタンスメソッドから定数を参照するには下記のようにconstructorを経由する必要があります。
export default class {
  static TEISU() { return 1; }

  instanceMethod() {
    // インスタンスメソッドから参照するにはconstructorを経由する必要がある
    alert(this.constructor.TEISU());
  }
}

staticな変数にすることもできるが定数にはならないので注意が必要

export default class {
  static TEISU = 1;

  instanceMethod() {
    this.constructor.TEISU = 2;// ここで値が書き換えられてしまう
    alert(this.constructor.TEISU);
  }
}

ちなみに、クラス名を指定している場合はクラス名.TEISU()のように呼べる

class Teisu {
  static TEISU() { return 1; }

  instanceMethod() {
    alert(Teisu.TEISU());
  }
}

参考文献

0
0
0

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
0