首页 > 解决方案 > 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();

标签: javascripttypescriptclass

解决方案


我通过使用以下类似代码完成了相同的任务:

假设我们必须创建一个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);

上述解决方案应该可以工作(但没有针对所有用例进行测试,但应该可以帮助您入门。)


推荐阅读