13

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.

2 Answers 2

22

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"
Sign up to request clarification or add additional context in comments.

1 Comment

perfect, thanks! EDIT: ooh, and I can put the class definitions into an object, instead of using the window object...
5

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();
};

3 Comments

It's only bad if you do not properly validate the string being evaled. Aside from that, this answer is great. The currently accepted answer only works if the class is globally accessible (i.e., at the window level). Classes defined within closures, for instance, cannot be instantiated using the window method.
@ElliotB. In that case, you can use this to reference the current scope. a la new this[className]
@JacobRelkin That doesn't appear to work. I constructed a test with scope referenced in a couple different ways: jsfiddle.net/d84bh/1 It only works for me when the class is defined at the global/window level: jsfiddle.net/d84bh/2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.