2

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");

2 Answers 2

3

If you know the object you're creating the variable on (a property, not just a variable) you can use 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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the help, Nick. In essence, we are creating a hash with dynamically named keys and values. genius.
3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.