Rare cases aside, eval() is considered bad practice in JavaScript.
I've just come across a fragment of code that takes a string and constructs an object by that type name. Error checking, business logic, and context for doing so removed, here's what it looks like:
function factory(klass) {
eval("var obj = new " + klass + "()"); // Is there a better way?
return obj;
}
Is there a better (safer, cleaner, and/or faster) way to accomplish the class creation without using eval?
I'm looking for a generic way to create a class by its name.
e.g., Imagine, for instance, another part of the code dynamically loads JavaScript files, generates code, or allows user extensions, but then some other part of the code needs to make that class without the factory having prior knowledge of its existence.
You can register classes with your factory object and than create them by string name:
var allClasses = [];
allClasses["MyClass"] = function(){return new MyClass();}
allClasses["MyStruct"] = function() {return {F1:"", F2:42};}
function factory(klass)
{
if (!allClasses[klass]) throw "Bad name!";
return allClasses[klass]();
}