2013-10-10 3 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 u 답변으로 표시해야합니다. – basarat

관련 문제