我尝试从抽象类的静态方法创建具体类的实例。但是我有这个错误:
未捕获的TypeError:对象原型只能是Object或为null: 未定义
在ConcreteClass.js中的这一行代码上:返回extendStatics(d,b);
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
我的项目文件:
Program.ts
import { AbstractClass } from "./AbstractClass";
class Program
{
public static Main()
{
let instance = AbstractClass.CreateObject();
instance.Method();
}
}
Program.Main();
AbstractClass.ts
import { ConcreteClass } from "./ConcreteClass";
export abstract class AbstractClass
{
public static CreateObject()
{
return new ConcreteClass();
}
public abstract Method(): void;
}
ConcreteClass.ts
import { AbstractClass } from "./AbstractClass";
export class ConcreteClass extends AbstractClass
{
public Method() : void
{
console.log("Method of ConcreteClass");
}
}
答案 0 :(得分:2)
问题与循环导入有关。 AbstractClass
和ConcreteClass
正在互相导入,并且每个的定义都在使用彼此。特定的问题是,当ConcreteClass
扩展AbstractClass
时,AbstractClass
仍未定义,因为它正在等待ConcreteClass
完成加载。结果,运行时模糊地看到了这样的东西:
import { AbstractClass } from "./AbstractClass";
// at runtime AbstractClass has not finished loading yet so it is undefined
export class ConcreteClass extends undefined
{
public Method() : void
{
console.log("Method of ConcreteClass");
}
}