如何在Typescript中访问基类的属性?

时间:2013-10-10 04:53:04

标签: inheritance properties typescript superclass

有人建议使用像这样的代码

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属性?

1 个答案:

答案 0 :(得分:38)

使用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());