create object from dynamic classname - ReflectionClass in JS?

后端 未结 2 597
鱼传尺愫
鱼传尺愫 2020-12-31 08:19

is it possible to do something like this without evil eval:

var str=\'MyClass\';
eval(\'new \'+str);

i just learned that there\'s Reflectio

2条回答
  •  执笔经年
    2020-12-31 09:02

    You could try this:

    var str = "MyClass";
    var obj = new window[str];
    

    Here's an example:

    function MyClass() {
       console.log("constructor invoked");
    }
    
    var s = "MyClass";
    new window[s]; //logs "constructor invoked"
    

提交回复
热议问题