Wednesday, June 5, 2024
 Popular · Latest · Hot · Upcoming
130
rated 0 times [  133] [ 3]  / answers: 1 / hits: 102129  / 11 Years ago, mon, march 11, 2013, 12:00:00

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

More From » typescript

 Answers
67

You could try:



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


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

[#79677] Saturday, March 9, 2013, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
maxinec

Total Points: 117
Total Questions: 116
Total Answers: 116

Location: Bangladesh
Member since Sat, Jan 23, 2021
3 Years ago
;