Ale*_*hin 17 inheritance properties superclass 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());
Run Code Online (Sandbox Code Playgroud)
它甚至得到了9票.但是当你将它粘贴在官方TS操场 http://www.typescriptlang.org/Playground/上时, 它会给你和错误.
如何从B访问A的x属性?
小智 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());
Run Code Online (Sandbox Code Playgroud)