2013-10-10 18 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