(继续前一次讨论"Dynamically loading a typescript class (reflection for typescript)")
如果我已经在命名空间内,有没有办法引用命名空间内的类来使用' reflection'打电话给他们的构造函数?
namespace Test {
interface INamed {
name:string;
}
class Foo implements INamed {
name:string;
constructor( name:string ) {
this.name = name;
}
}
class Bar implements INamed {
name:string;
constructor( name:string ) {
this.name = name;
}
}
export function factory( className:string ):INamed {
var str = className + " instance";
var t;
/*
// how to 'reflect' inside namespace Test to get Test.Foo or Test.Bar?
t = new window[className]( str );
t = new context[className]( str );
t = new this.context[className]( str );
t = new this[className]( str );
t = new Test[className]( str );
*/
t = new Bar( str );
return t;
}
}
然后(不得不拆掉它以便SO不会失去它,无论如何)
var bar = Test.factory( "Bar" );
console.log( bar.name );
答案 0 :(得分:1)
namespace Test {
interface INamed {
name:string;
}
export class Foo implements INamed {
name:string;
constructor( name:string ) {
this.name = name;
}
}
export class Bar implements INamed {
name:string;
constructor( name:string ) {
this.name = name;
}
}
export function factory( className:string ):INamed {
return new Test[className]( className + " instance" );
}
}
var bar = Test.factory( "Bar" );
console.log( bar.name );