Typescript: 継承と静的メンバー

作成日 2015年12月08日  ·  1コメント  ·  ソース: microsoft/TypeScript

私はそれが静的メンバーへのアクセスに役立つと思います:

  • インスタンスから
  • サブクラスから

例の下:

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'
By Design Declined Suggestion

最も参考になるコメント

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_プロパティにアクセスするために使用されるため、提案した方法でそれを行うことはできません。

ただし、次のように記述すれば、例は機能します。

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を介して統計にアクセスでき、実際にインスタンスを作成したコンストラクターオブジェクト(つまり、派生コンストラクターオブジェクト)のプロパティを取得できます。

このページは役に立ちましたか?
0 / 5 - 0 評価