【问题标题】:How can I access the superclass value of a getter in a subclass?如何访问子类中 getter 的超类值?
【发布时间】:2013-01-04 20:17:24
【问题描述】:

在派生类中访问gettersuper 值似乎不起作用:

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"

如何正确覆盖 getter 并使用 super 值?

【问题讨论】:

  • 这只是 TypeScript 继承中的许多“陷阱”之一。 TS 看起来非常像 C#,以至于它让你误以为它的行为也像 C#。有关更多信息,请参阅blog.wouldbetheologian.com/2012/11/… :-(.

标签: javascript inheritance overriding typescript


【解决方案1】:

我不一定赞同您继续采用这种方法,但是...

class Bar extends Foo {
    public get Message():string {
        return Object.getOwnPropertyDescriptor(Foo.prototype, 'Message').get.apply(this) +  ' World';
    }   
}

原型继承并没有让这变得特别简单。

【讨论】:

  • 谢谢。我有一个特定模型(级联打印样式)形式的外部约束,它大量使用覆盖的属性 - 这种方法至少让我可以在 TS 中使用它。
猜你喜欢
  • 2012-04-09
  • 1970-01-01
  • 1970-01-01
  • 2021-05-24
  • 2013-06-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-08
相关资源
最近更新 更多