考虑以下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
的方法可以访问新值?