0

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"
Patrik Fröhler
  • 1,221
  • 1
  • 11
  • 38
  • 2
    Either make it part of an object (one of your own of `window` if you wish to have it global), otherwise `eval`. There's a very strong [XY problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) smell in your question. – Kyll Jun 14 '16 at 15:43
  • Why do you think you need to do this? How is that better than returning the object? `var theFirstVarName = createNewObj("Car", 10, "red")` –  Jun 14 '16 at 15:43
  • 2
    Dynamically named globals are a terrible idea. – Quentin Jun 14 '16 at 15:44
  • Why not just `theFirstVarName = createNewObj("Car", 10, "red" );`? It's almost the same, but easier to understand, use and maintain. – Álvaro González Jun 14 '16 at 15:46
  • Well what I'm trying to do is have multiple generated divs with jquery lets call them "cards" the div id of them will be dynamically generated and then i want to store all the data for that card in an object, then I want to have with jquery when you click that "div card" it gets the data for that card and transfers it to another function, might be better ways of doing it but this is what i'm currently trying. – Patrik Fröhler Jun 14 '16 at 15:47
  • 1
    So then it is an XY Problem. –  Jun 14 '16 at 15:47

1 Answers1

2

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);
Stephan Bijzitter
  • 4,425
  • 5
  • 24
  • 44
  • 1
    Sometimes the best help you can give someone is to *not* show them how to do what they think they need to do. –  Jun 14 '16 at 15:49
  • 1
    But where do you stop? Surely we can take a look at his code and point out more than one problem and we can completely redesign all of it. Even when it's perfect, we could still do that. He asked a specific question, so a specific answer is what is expected. If this strategy later does not seem to work very well, I'm sure we can expect a new question ;-) – Stephan Bijzitter Jun 14 '16 at 15:56
  • 1
    Probably stop before giving solutions that really ought not be used in most cases. Beginners (including future readers) have a tendency to use the first solution that appears to "work", and end up writing bad code for a long time because of it. A correct answer isn't necessarily a good answer. –  Jun 14 '16 at 17:15