As you are using TypeScript I'm assuming you want the loaded object to be typed. So here is the example class (and an interface because you are choosing to load one of many implementations, for example).
interface IExample {
test() : string;
}
class Example {
constructor (private a: string, private b: string) {
}
test() {
return this.a + ' ' + this.b;
}
}
So you would use some kind of loader to give you back an implementation:
class InstanceLoader {
constructor(private context: Object) {
}
getInstance(name: string, ...args: any[]) {
var instance = Object.create(this.context[name].prototype);
instance.constructor.apply(instance, args);
return instance;
}
}
And then load it like this:
var loader = new InstanceLoader(window);
var example = <IExample> loader.getInstance('Example', 'A', 'B');
alert(example.test());
At the moment, we have a cast: <IExample>
- but when generics are added, we could do away with this and use generics instead. It will look like this (bearing in mind it isn't part of the language yet!)
class InstanceLoader<T> {
constructor(private context: Object) {
}
getInstance(name: string, ...args: any[]) : T {
var instance = Object.create(this.context[name].prototype);
instance.constructor.apply(instance, args);
return <T> instance;
}
}
var loader = new InstanceLoader<IExample>(window);
var example = loader.getInstance('Example', 'A', 'B');