一尘不染

动态加载一个打字稿类(反映打字稿)

javascript

我希望能够实例化一个Typescript类,在运行时可以获取该类和构造函数的详细信息。我想编写的函数将包含类名和构造函数参数。

export function createInstance(moduleName : string, className : string, instanceParameters : string[]) {
    //return new [moduleName].[className]([instancePameters]); (THIS IS THE BIT I DON'T KNOW HOW TO DO)
}

阅读 245

收藏
2020-05-01

共1个答案

一尘不染

您可以尝试:

var newInstance = Object.create(window[className].prototype);
newInstance.constructor.apply(newInstance, instanceparameters);
return newInstance;

编辑 此版本可在TypeScript操场上使用,例如:

class Greeter {
    greeting: string;
    constructor(message: string) {
        this.greeting = message;
    }
    greet() {
        return "Hello, " + this.greeting;
    }
}

//instance creation here
var greeter = Object.create(window["Greeter"].prototype);
greeter.constructor.apply(greeter, new Array("World"));

var button = document.createElement('button');
button.innerText = "Say Hello";
button.onclick = function() {
    alert(greeter.greet());
}

document.body.appendChild(button);
2020-05-01