static キーワードは、クラスに静的メソッドを定義します。
構文
static methodName() { ... }
説明
静的メソッドは、クラスのインスタンスを作らず呼び出せるメソッドです。またインスタンスができると呼び出せません。静的メソッドはアプリケーションのユーティリティ関数を作る際によく使われます。
静的メソッドの呼び出し
他の静的メソッドから
同じクラス内の静的メソッドを静的メソッドから呼び出すには、this キーワードを使います。
class StaticMethodCall {
static staticMethod() {
return 'Static method has been called';
}
static anotherStaticMethod() {
return this.staticMethod() + ' from another static method';
}
}
StaticMethodCall.staticMethod();
// 'Static method has been called'
StaticMethodCall.anotherStaticMethod();
// 'Static method has been called from another static method'
クラスのコンストラクタや他のメソッドから
静的メソッドは this キーワードから直接呼び出せません。呼び出すには CLASSNAME.STATIC_METHOD_NAME という風に、クラス名をメソッドの前につけないといけません(クラス外で静的メソッドを呼び出すのと同じやり方です)。もしくは、this.constructor.STATIC_METHOD_NAME と、constructor プロパティを使います。
class StaticMethodCall{
constructor(){
console.log(StaticMethodCall.staticMethod());
// 'static method has been called'
console.log(this.constructor.staticMethod());
// 'static method has been called'
}
static staticMethod(){
return 'static method has been called.';
}
}
例
次のコードは、静的メソッドがどうクラスで実装されているか、また静的メンバを持つクラスのサブクラスをどう作るか、そして静的メソッドがどう呼び出せる・または呼び出せないかを説明しています。
class Triple {
static triple(n) {
if (n === undefined) {
n = 1;
}
return n * 3;
}
}
class BiggerTriple extends Triple {
static triple(n) {
return super.triple(n) * super.triple(n);
}
}
console.log(Triple.triple()); // 3
console.log(Triple.triple(6)); // 18
console.log(BiggerTriple.triple(3)); // 81
var tp = new Triple();
console.log(BiggerTriple.triple(3));
// 81 (not affected by parent's instantiation)
console.log(tp.triple());
// 'tp.triple is not a function'.
仕様
| 仕様 | ステータス | コメント |
|---|---|---|
| ECMAScript 2015 (6th Edition, ECMA-262) クラスの定義 の定義 |
標準 | 導入された |
| ECMAScript 2017 Draft (ECMA-262) クラスの定義 の定義 |
ドラフト |
ブラウザ実装状況
| 機能 | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
|---|---|---|---|---|---|
| 基本サポート | 42.0 | 45 (45) | ? | ? | ? |
| 機能 | Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile | Chrome for Android |
|---|---|---|---|---|---|---|
| 基本サポート | 未サポート | 45.0 (45) | ? | ? | ? | 42.0 |