Patrik Fröhler Patrik Fröhler -5 years ago 101
Javascript Question

Create dynamically named javascript objects?

How can I create javascript objects that are "named" dynamically?

Here is a non working example of what I'm trying to do, the issue is with:

"objVarName = "



function CustomObj(pName, pAge, pColor) { = pName,
this.age = pAge,
this.color = pColor

function createNewObj (objVarName, pName, pAge, pColor){
objVarName = new CustomObj(pName, pAge, pColor);

createNewObj("theFirstVarName", "Car", 10, "red" );

alert(; // if working should alert "Car"

Answer Source

You can do this by changing one line, but I'm not sure why you would want this:

objVarName = new CustomObj(pName, pAge, pColor);


window[objVarName] = new CustomObj(pName, pAge, pColor);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download