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 n开发者_开发技巧ame = "fifi";
[name] = new Dog(name);
to achieve the same outcome as:
fifi = new Dog("fifi");
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
.
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.
精彩评论