最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I access the superclass value of a getter in a subclass? - Stack Overflow

programmeradmin1浏览0评论

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?

Share Improve this question edited Jan 21, 2013 at 23:57 Ryan Cavanaugh 222k59 gold badges279 silver badges235 bronze badges asked Jan 21, 2013 at 17:46 Jude FisherJude Fisher 11.3k9 gold badges53 silver badges92 bronze badges 1
  • 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
Add a ment  | 

1 Answer 1

Reset to default 8

I'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.

发布评论

评论列表(0)

  1. 暂无评论