TypeScript:子类如何覆盖其父类的属性?

时间:2017-10-26 19:41:34

标签: typescript inheritance

考虑以下TypeScript代码:

abstract class AbstractTable {

    protected objectStoreName: string = 'abstract';

    constructor() {
        console.log('in AbstractTable constructor; this.objectStoreName is:');
        console.log(this.objectStoreName);
        // TODO: some kind of initialization that uses this.objectStoreName
    }

}

class ConcreteTable extends AbstractTable {

    protected objectStoreName: string = 'concrete';

    constructor() {
        super();
        console.log('in ConcreteTable constructor; this.objectStoreName is:');
        console.log(this.objectStoreName);
    }

}

var table = new ConcreteTable();

这里的输出我预期

in AbstractTable constructor; this.objectStoreName is:
concrete
in ConcreteTable constructor; this.objectStoreName is:
concrete

这是我实际得到的输出

in AbstractTable constructor; this.objectStoreName is:
abstract
in ConcreteTable constructor; this.objectStoreName is:
concrete

我不明白这一点。我只有一个对象:ConcreteTable类的一个实例。 this关键字引用该实例,无论我是在父类还是子类中使用this。那么:this.objectStoreName怎么可能会返回两个不同的值,具体取决于它所在的类?

或许更重要的是: ConcreteClass如何覆盖objectStoreName,以便AbstractClass的方法可以访问新值?

0 个答案:

没有答案