→
static キーワードは、クラスに静的メソッドや静的プロパティを定義します。
静的メソッドも静的プロパティもクラスのインスタンスからは呼び出されません。その代わりに、クラスそのものから呼び出されます。静的メソッドは多くの場合、オブジェクトの生成や複製を行う関数などのユーティリティ関数です。静的プロパティはキャッシュ、固定的な構成、その他の各インスタンスに複製する必要のないデータです。
次の例はいくつかのことを説明しています:
//コンソールにて
class Triple{
static customName = 'Tripler';
static description = 'I triple any number you provide';
static calculate(n = 1) {
return n * 3;
}
}
class SquaredTriple extends Triple{
static longDescription;
static description = 'I square the triple of any number you provide';
static calculate(n) {
return super.calculate(n) * super.calculate(n);
}
}
console.log(Triple.description); // 'I triple any number you provide'
console.log(Triple.calculate()); // 3
console.log(Triple.calculate(6)); // 18
const tp = new Triple();
console.log(SquaredTriple.calculate(3)); // 81 (not affected by parent's instantiation)
console.log(SquaredTriple.description); // 'I square the triple of any number you provide'
console.log(SquaredTriple.longDescription); // undefined
console.log(SquaredTriple.customName); // 'Tripler'
// This throws because calculate() is a static member, not an instance member.
console.log(tp.calculate()); // 'tp.calculate is not a function'
同じクラス内の静的メソッドまたはプロパティを静的メソッドから呼び出すには、this キーワードを使います。
class StaticMethodCall {
static staticProperty = 'static property';
static staticMethod() {
return 'Static method and ' + this.staticProperty + ' has been called';
}
static anotherStaticMethod() {
return this.staticMethod() + ' from another static method';
}
}
StaticMethodCall.staticMethod();
// 'Static method and static property has been called'
StaticMethodCall.anotherStaticMethod();
// 'Static method and static property has been called from another static method'
静的メソッドは静的ではないメソッドの this キーワードを使用して直接アクセスすることができません。呼び出すにはクラス名を使用して クラス名.静的メソッド名()/クラス名.静的プロパティ名 のようにするか、 constructor プロパティのメソッドとして this.constructor.静的メソッド名()/this.constructor.静的プロパティ名 のようにしてください。
コンソールにて
class StaticMethodCall {
constructor() {
console.log(StaticMethodCall.staticProperty); // 'static property'
console.log(this.constructor.staticProperty); // 'static property'
console.log(StaticMethodCall.staticMethod()); // 'static method has been called.'
console.log(this.constructor.staticMethod()); // 'static method has been called.'
}
static staticProperty = 'static property';
static staticMethod() {
return 'static method has been called.';
}
}
class CS1{
static P1="P1の初期値です";
P2="P2の初期値です";
}
D=CS1.P1; //="P1の初期値です"
C1=new CS1();
D=C1.P1; //=undefined
C1.P1="テスト"; //書き換えてみる
D=C1.P1; //="テスト"
class CS2 extends CS1{
}
C2=new CS2();
D=C2.P1; //=undefined
D=C2.P2; //="P2の初期値です"