How do you dynamically name and create an object in javascript?
-
normally to create an object you would write: function Dog(name) { this.name = name; } fifi = new Dog("fifi"); How do I dynamically name the object so that I can write: var name = "fifi"; [name] = new Dog(name); to achieve the same outcome as: fifi = new Dog("fifi");
-
Answer:
If you know the object you're creating the variable on (a property, not just a variable) you can use https://developer.mozilla.org/en/JavaScript/Reference/Operators/Member_Operators#Bracket_notation, like this: var dogs = {}; dogs[name] = new Dog(name); Later you could access it either way: dogs.fifi //or... dogs["fifi"] If it's a global variable you're after, that object (instead of dogs above) would just be window.
Anthony H at Stack Overflow Visit the source
Other answers
This would do it: function createDog(name, scope) { scope[name] = new Dog(name); } Then you could do: createDog('fifi', window); or pass any other object as your scope. But I would not tie objects and variables to close together. One advantage of objects is that you can pass them freely around and several variables can have a reference to the same object. I would give it a more meaningful name, that describes the purpose of that object.
Felix Kling
Related Q & A:
- How can I save an Icollection in an object?Best solution by Stack Overflow
- How to create an SlideShow in javascript?Best solution by Stack Overflow
- How can I dynamically change the height of an iFrame?Best solution by Stack Overflow
- How to create dynamic function in javascript?Best solution by Stack Overflow
- How to create an Object with multiple properties of the same name?Best solution by javascript.info
Just Added Q & A:
- How many active mobile subscribers are there in China?Best solution by Quora
- How to find the right vacation?Best solution by bookit.com
- How To Make Your Own Primer?Best solution by thekrazycouponlady.com
- How do you get the domain & range?Best solution by ChaCha
- How do you open pop up blockers?Best solution by Yahoo! Answers
For every problem there is a solution! Proved by Solucija.
-
Got an issue and looking for advice?
-
Ask Solucija to search every corner of the Web for help.
-
Get workable solutions and helpful tips in a moment.
Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.