Typescript 为什么抽象方法实现中的this.propertyName引用错误?
为什么在下面的代码中我错了这个.name引用在抽象方法实现中Typescript 为什么抽象方法实现中的this.propertyName引用错误?,typescript,Typescript,为什么在下面的代码中我错了这个.name引用在抽象方法实现中 abstract class Abstract { protected name: string; constructor () { this.abstractMethod(); } protected abstract abstractMethod (): void; } class Concrete extends Abstract { protected name: string = 'Conc
abstract class Abstract {
protected name: string;
constructor () {
this.abstractMethod();
}
protected abstract abstractMethod (): void;
}
class Concrete extends Abstract {
protected name: string = 'Concrete';
protected abstractMethod () {
console.log(this, this.name); // Concrete, undefined
}
}
new Concrete();
查看编译后的JavaScript在以下情况下会有所帮助:
function Concrete() {
_super.apply(this, arguments); // calls this.abstractMethod()
this.name = 'Concrete';
}
直到超级调用调用
Abstract
的构造函数之后,作业才会发生,所以在这个时候,abstractMethod
被称为this。name
是未定义的我真的不知道,你想要实现什么,但也许这有帮助,对不起我的英语
abstract class Abstract {
protected name: string;
constructor () {
//this.abstractMethod();
}
protected abstract abstractMethod (): void;
}
class Concrete extends Abstract {
protected name: string = 'Concrete';
constructor () {
super();
this.abstractMethod();
}
protected abstractMethod () {
console.log(this, this.name);
}
}
控制台:
Concrete { name: 'Concrete' } 'Concrete'
您观察到的现象是可以预测的,因为构造函数按照从基类到具体类的顺序运行。最佳修复方法是让抽象类构造函数处理name属性:
abstract class Abstract {
constructor (protected name: string) {
this.abstractMethod();
}
protected abstract abstractMethod (): void;
}
class Concrete extends Abstract {
constructor() {
super("Concrete");
}
protected abstractMethod () {
console.log(this, this.name); // Concrete, undefined
}
}
new Concrete();
你确定吗?我在我的IDE上也没有发现链接上的错误。在c#、java或javascript中从构造函数调用虚拟方法通常不是一个好主意,因为类型不变量可能会中断。(请参阅Eric Lipperts的帖子,了解它有什么问题,特别是评论部分)有什么更好的方法来解决这个问题?@kаааааааааааааааааа107。