私はそれが静的メンバーへのアクセスに役立つと思います:
例の下:
class A {
protected static type: string;
public log(): string {
console.log(this.type);
}
}
class B extends A {
protected static type: string = 'C';
}
class C extends A {
protected static type: string = 'C';
}
b = new B();
b.log(); // => 'B'
c = new C();
c.log(); // => 'C'
this.type
は、_static_プロパティではなく、 type
という名前の_instance_プロパティにアクセスするために使用されるため、提案した方法でそれを行うことはできません。
ただし、次のように記述すれば、例は機能します。
class A {
"constructor": typeof A; // Explicitly declare constructor property
protected static type: string;
public log() {
console.log(this.constructor.type); // Access actual constructor object
}
}
class B extends A {
protected static type: string = 'B';
}
class C extends A {
protected static type: string = 'C';
}
let b = new B();
b.log(); // => 'B'
let c = new C();
c.log(); // => 'C'
デフォルトでは、インスタンスのconstructor
プロパティはタイプFunction
ですが、手動で宣言することでクラスに特化できます。 これを行うと、 this.constructor.xxx
を介して統計にアクセスでき、実際にインスタンスを作成したコンストラクターオブジェクト(つまり、派生コンストラクターオブジェクト)のプロパティを取得できます。
最も参考になるコメント
this.type
は、_static_プロパティではなく、type
という名前の_instance_プロパティにアクセスするために使用されるため、提案した方法でそれを行うことはできません。ただし、次のように記述すれば、例は機能します。
デフォルトでは、インスタンスの
constructor
プロパティはタイプFunction
ですが、手動で宣言することでクラスに特化できます。 これを行うと、this.constructor.xxx
を介して統計にアクセスでき、実際にインスタンスを作成したコンストラクターオブジェクト(つまり、派生コンストラクターオブジェクト)のプロパティを取得できます。