Accessing the super
value of a getter
in a derived class doesn't seem to work:
class Foo {
private _message:string = "Hello,";
public get Message():string {
return this._message;
}
}
class Bar extends Foo {
public get Message():string {
return super.Message + " World";
}
}
var snafu:Bar = new Bar();
document.write(snafu.Message);
// Expected: "Hello, World"
// Actual: "undefined World"
How can I correctly override a getter
and make use of the super
value?
Accessing the super
value of a getter
in a derived class doesn't seem to work:
class Foo {
private _message:string = "Hello,";
public get Message():string {
return this._message;
}
}
class Bar extends Foo {
public get Message():string {
return super.Message + " World";
}
}
var snafu:Bar = new Bar();
document.write(snafu.Message);
// Expected: "Hello, World"
// Actual: "undefined World"
How can I correctly override a getter
and make use of the super
value?
- 3 This is just one of many "gotchas" in TypeScript inheritance. TS looks so much like C# that it fools you into thinking that it acts like C# too. See blog.wouldbetheologian./2012/11/… for several more :-(. – Ken Smith Commented Jan 22, 2013 at 3:03
1 Answer
Reset to default 8I'm not necessarily endorsing that you continue with this approach, but...
class Bar extends Foo {
public get Message():string {
return Object.getOwnPropertyDescriptor(Foo.prototype, 'Message').get.apply(this) + ' World';
}
}
Prototypal inheritance doesn't make this particularly straightforward.