javascript - Create a new object from a class name and pass the class name as string
问题描述
Based on this https://stackoverflow.com/a/46656181/8577819, I have created a function to return an object for a class.
function getInstance<T extends Object>(type: (new (...args: any[]) => T), ...args: any[]): T {
return new type(...args);
}
class testclass {
x: string;
constructor(x:string) {
this.x=x;
}
printcon() {
console.log("printing from test " + this.x);
}
}
var dds: testclass = getInstance(testclass,10);
dds.printcon();
/// Console prints
// printing from test 10
Is it possible to pass the class name itself as a string argument to the object creator?
clnm: string = "testclass";
var dds2: <clnm> = getInstance(clnm,10);
dds2.printcon();
解决方案
我通过使用以下类似代码完成了相同的任务:
假设我们必须创建一个Instance
位于modules
文件夹下的类。
modules/Calulator.ts
在构造函数中也需要一个参数:
export class Calculator {
c: number;
constructor(cc: number) {
this.c = cc;
}
sum(a: number, b: number): number {
return a + b + Number(this.c);
}
}
我们的InstanceBuilder
课程没有使用eval
(也使用了注释的工作代码eval
):
import * as wfModule from "../modules";
export class InstanceBuilder {
getInstance(className: string, ...args: any[]): any {
// TODO: Handle Null and invalid className arguments
const mod: any = wfModule;
if (typeof mod[className] !== undefined) {
return new mod[className](args);
} else {
throw new Error("Class not found: " + className);
}
// Other working methods:
// const proxy: any = undefined;
// const getInstance = (m) => eval("obj = Object.create(m." + className + ".prototype);");
// eval("obj = new mod['" + className + "'](" + args + ")");
// eval("proxy.prototype = Object.create(mod." + className + ".prototype);");
// obj.constructor.apply(args);
}
}
然后,要动态创建类,您可以执行以下操作:
const instanceBuilder = new InstanceBuilder();
const commandInstance = instanceBuilder.getInstance("Calculator", initArgsValues);
上述解决方案应该可以工作(但没有针对所有用例进行测试,但应该可以帮助您入门。)
推荐阅读
- scala - Scala akka 键入:如何从它的实例中获取 ActorRef 到 Actor 并自己发送消息?
- delphi - 如果程序未提升,OpenProcess() 返回 ERROR_ACCESS_DENIED
- java - Hbox 有子 Buttons ,如何抓取和添加监听器?
- android - Android openGL ES 3.0 着色器不工作
- cloudconvert - API CloudConvert curl 请求 PHP
- authentication - 无法授予 MS Asure 图形 API 客户端应用程序获取有关 ManagedDevices 的数据的权限。如何克服?
- sql-server - Subshell 中的 Bash BG 进程:显示输出以及管道到命令(Docker CMD 启动 Shell 脚本)
- python - 尝试在某个日期范围内抓取 google 的结果数量错误
- ajax - 如何从 MVC ViewModel 获取输入数据到 ajax post
- python - Python - 将导入转换为模块格式