create object from dynamic classname - ReflectionClass in JS?

后端 未结 2 620
鱼传尺愫
鱼传尺愫 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:18

    Create object (invoke constructor) via reflection:

    SomeClass = function(arg1, arg2) {
        // ...
    }
    
    ReflectUtil.newInstance('SomeClass', 5, 7);
    

    and implementation:

    /**
     * @param strClass:
     *          class name
     * @param optionals:
     *          constructor arguments
     */
    ReflectUtil.newInstance = function(strClass) {
        var args = Array.prototype.slice.call(arguments, 1);
        var clsClass = eval(strClass);
        function F() {
            return clsClass.apply(this, args);
        }
        F.prototype = clsClass.prototype;
        return new F();
    };
    

提交回复
热议问题