我可以动态调用名称为字符串的静态函数吗?经过一番尝试后,我可以得到所有:
class Test{
static Instance(){
console.log( "Instantiated" );
};
};
Test.Instance();//<-- ok
var testVar = "Test";
eval( testVar + ".Instance()" ); // ok but eval is evil!
window[testVar].Instance();//<-- undefined is not an object (evaluating 'window[testVar].Instance')
答案 0 :(得分:3)
您可以使用new Function
Stack snippet
class Test {
static Instance() {
console.log("Instantiated");
};
};
var testVar = "Test";
var func = function(string) {
return (new Function('return (' + string + ').Instance()')());
}
func(testVar);
&#13;
以下是关于new Function
与eval