本文介绍了动态加载typescript类(打字稿的反射)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望能够实例化一个typescript类,在运行时获取类和构造函数的详细信息。
我想写的函数将包含类名和构造函数参数。
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);
这篇关于动态加载typescript类(打字稿的反射)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!