我得到当前的错误:
Uncaught ReferenceError: can't access lexical declaration 'AbstractClass' before initialization
在新的 Angular 项目中执行此操作时:
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
title = '';
ngOnInit() {
console.log(JSON.stringify(new (AbstractClass.get("MyId1"))()))
}
}
而且我不明白为什么会发生这种情况,因为我首先引用了一个静态方法,然后实例化函数返回的类引用,然后在新初始化的类上调用一个函数......
抽象类.ts
export abstract class AbstractClass {
abstract getModelName(): string;
public static get(id: string): Type<AbstractClass> {
switch (id) {
case "MyId1":
return MyId1ImplementationClass;
case "MyId2":
return MyId2ImplementationClass;
default:
return MyId1ImplementationClass;
}
}
}
MyId1ImplementationClass.ts
export class MyId1ImplementationClass extends AbstractClass {
getModelName(): string {
return "Id1!";
}
}
MyId2ImplementationClass.ts
export class MyId2ImplementationClass extends AbstractClass {
getModelName(): string {
return "Id2!";
}
}