动态加载打字稿类(打字稿的反射) [英] Dynamically loading a typescript class (reflection for typescript)

查看:43
本文介绍了动态加载打字稿类(打字稿的反射)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够实例化一个打字稿类,在那里我可以在运行时获取类和构造函数的详细信息.我想写的函数将接受类名和构造函数参数.

I would like to be able to instantiate a typescript class where I get the class and constructor details at runtime. The function I would like to write will take in the class name and constructor parameters.

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)
}

推荐答案

你可以试试:

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

编辑此版本正在使用 TypeScript 游乐场,例如:

Edit This version is working using the TypeScript playground, with the example:

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);

这篇关于动态加载打字稿类(打字稿的反射)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆