20

このようなコードを使用する提案がありました

class A {
    // Setting this to private will cause class B to have a compile error
    public x: string = 'a';
}

class B extends A {
    constructor(){super();}
    method():string {
        return super.x;
    }
}

var b:B = new B();
alert(b.method());

しかも9票も獲得。しかし、公式の TS プレイグラウンド http://www.typescriptlang.org/Playground/ に貼り付けると、エラーが発生します。

BからAのxプロパティにアクセスするには?

4

1 に答える 1

45

thisではなく使用super:

class A {
    // Setting this to private will cause class B to have a compile error
    public x: string = 'a';
}

class B extends A {
    // constructor(){super();}
    method():string {
        return this.x;
    }
}

var b:B = new B();
alert(b.method());
于 2013-10-10T05:13:16.683 に答える