Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create object from dynamic classname - ReflectionClass in JS?

Tags:

javascript

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

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

i just learned that there's ReflectionClass in PHP... thanks.

like image 228
kubi Avatar asked Feb 22 '11 23:02

kubi


2 Answers

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"
like image 188
Jacob Relkin Avatar answered Nov 05 '22 06:11

Jacob Relkin


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();
};
like image 45
Mike Avatar answered Nov 05 '22 05:11

Mike