Ian Chadwick
Ian Chadwick

Reputation: 1627

Javascript object instantiation similar to php new $className();

I'm trying to do the equivalent to this but in JS.

$className = 'MyClass';
$obj = new $className();

I've tried obvious things but with no luck, currently resorted to using eval as below :/

eval('var model = ' + modelName + '();');

Thanks!

Upvotes: 1

Views: 640

Answers (2)

Rob W
Rob W

Reputation: 349142

For global "classes", use:

var classname = "Date";
var obj = new window[classname]();

window is the global namespace. Variables and methods defined immediately within <script>, without a wrapper are automatically stored in the global namespace.

For methods of other "namespaces", use:

var classname = "round";
var obj = new Math[funcname]();
// Illustrative purposes only, Math doesn't need `new`

For private methods which aren't attached to a namespace, there's no solution except for eval or Function:

var classname = "nonglobal";
var obj = new (Function(classname))();

You should avoid eval whenever possible, especially if you're working with unknown strings.

Upvotes: 5

jmoreno
jmoreno

Reputation: 13571

See this SO question for a good anwser: Dynamic Object Creation

But basically you want return new window[modelName];

Upvotes: 1

Related Questions