javascript - 从类名创建一个新对象并将类名作为字符串传递

标签 javascript typescript class

基于此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/

相关文章:

javascript - Angular 2 基础知识

typescript - 使用 'as Movie[]' 而不是 '<Movie[]>' @typescript-eslint/consistency-type-assertions

c++ - 具有不同类成员选择的同一类对象 (C++)

sql - 如何在typeorm querybuilder中选择特定列

c++ - 如何创建 "weak"函数并将其用于对象?

c++ - 当有多个构造函数时如何设置默认构造函数

javascript - 弹出窗口 jQ​​uery

javascript - 使用 Primefaces JavaScript 在服务器上的 bean 上调用 JSF 方法

javascript - VUE - [食物配料计数器] 单击 "+ add"按钮时如何增加 v-for 列表 -of toppings- 中元素 -topping- 的值

javascript - 如何添加基于 URL 结构的动态主体类?