Possible Duplicate:
create object from dynamic classname - ReflectionClass in JS?
Is it possible to do this in javascript?
var objectName = "object";
var object = new objectName();
or something along these lines?
Possible Duplicate:
create object from dynamic classname - ReflectionClass in JS?
Is it possible to do this in javascript?
var objectName = "object";
var object = new objectName();
or something along these lines?
If the constructor is defined globally...
var object = new window[objectName]();
If not, you'd need to use eval or the Function constructor. Before you did that, I'd try to find a different way to do what you're doing.
var objectName = "Object";You can archieve that using eval(). Eval basically interprets a string like it were a script line. Althought, some developers consider it's a dangerous function to your daily use, other's don't. Read more here.
Example of your code using eval (corrected):
var objectName = "Object";
var object = new (eval(objectName));
eval("object.name = \"Nice!\""); // you don't need this, just an example of eval capabilities
document.write(object.name);
Running: http://jsfiddle.net/RxNsd/4/
var objectName = "Object";var object = new (eval(objectName));.No, it's not possible the way you coded. But with a little change...
var object = { objectName: "object" };
alert(object.objectName); // Pops up "object"
If you prefer the new syntax, there must exist a constructor function.
function ObjectName(name) // This is the "constructor" function
{
this.objectName = name;
}
var object = new ObjectName("object");
alert(object.objectName); // Pops up "object"