Patrik Fröhler Patrik Fröhler - 5 months ago 11
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 = "


JSFIDDLE DEMO

JavaScript[CODE]:

function CustomObj(pName, pAge, pColor) {
this.name = 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(theFirstVarName.name); // if working should alert "Car"

Answer

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

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

to:

window[objVarName] = new CustomObj(pName, pAge, pColor);
Comments