基于此https://stackoverflow.com/a/46656181/8577819 ,我创建了一个函数来返回类的对象。
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
是否可以将类名本身作为字符串参数传递给对象创建者?
clnm: string = "testclass";
var dds2: <clnm> = getInstance(clnm,10);
dds2.printcon();
最佳答案
我使用以下类似的代码完成了相同的任务:
假设我们必须在 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);
上述解决方案应该有效(但尚未针对所有用例进行测试,但应该可以帮助您入门。)
关于javascript - 从类名创建一个新对象并将类名作为字符串传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57302732/