2013-10-10 17 views
11

有使用這樣如何在Typescript中訪問基類的屬性?

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

回答

27

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

冠軍!對不起,沒有足夠的信譽+1 –

+4

@AlexVaghin你可以/應該標記爲答案 – basarat