我有一个 Typescrip 应用程序,我需要在其中实现代表不同控制逻辑的不同类(例如ControlLogicA、ControlLogicB、ControlLogicC)。所有这些类都是同一个抽象超类 ( ControlLogicAbstract) 的扩展。
要应用的控制逻辑是在配置时确定的,因此,在运行时,我唯一知道的是我需要以字符串形式(例如controlLogicClassName)使用的类的名称。
现在问题:
1) 是否可以在 Typescript 中仅从类的名称开始创建类的实例(例如,只知道controlLogicClassName)?
2)是否可以在浏览器环境和节点环境中执行此操作?
3)如果这可以在浏览器环境中完成,旧版本的浏览器(比如IE9及更高版本)是否也支持它?
附加问题:是否可以(在运行时)查询抽象 Typescript 类(例如ControlLogicAbstract)以获取其所有可用子类的列表(在我的示例 ControlLogicA、ControlLogicB 和 ControlLogicC 中)?
提前致谢
你可以有类似的东西:
interface ControlLogicConstrctor {
new (): ControlLogicAbstract;
}
abstract class ControlLogicAbstract {}
class ControlLogic1 extends ControlLogicAbstract {}
class ControlLogic2 extends ControlLogicAbstract {}
var ctors: { [name: string]: ControlLogicConstrctor } = {
"control1": ControlLogic1,
"control2": ControlLogic2,
// ...
"controlN": ControlLogicN
}
function factory(name: string): ControlLogicAbstract {
let ctor = ctors[name];
if (!ctor) {
return null;
}
return new ctor();
}
Run Code Online (Sandbox Code Playgroud)
这在浏览器和节点中应该可以正常工作。
基本上在 javascript 中,这些类只是函数,例如:
class MyClass {
private x: number;
constructor() {
this.x = 4;
}
}
Run Code Online (Sandbox Code Playgroud)
编译成:
var MyClass = (function () {
function MyClass() {
this.x = 4;
}
return MyClass;
}());
Run Code Online (Sandbox Code Playgroud)
所以你最终MyClass只是一个函数。
不,您无法获得所有扩展类。
这在 ts/js 中不受支持,您需要以某种方式自己处理(例如拥有一个包含类/ctors 的数据结构,有点像我的ctors对象)。