Reputation: 195
Here's what I'm trying to accomplish. I'm creating objects dynamically and I want to add them to a "master container" object. I'm currently using arrays for containers, but sometimes I'd like to access these objects by name instead of by index. Such as:
function Scene() {
this.properties;
}
Scene.prototype.addEntity = function(entity) {
this.push(entity);
}
var coolNameForObject = { Params };
var Scene1 = new Scene();
Scene1.addEntity(coolNameForObject);
I know the .push isn't available, only for arrays, but I'm tired of using indexes all day. I'd like to reference each entity by it's name. e.g:
Scene1.coolNameForObject.property
But can't think of a good way to do it.
Maybe have something like:
coolNameForObject.name = 'coolNameForObject';
Scene1.(coolNameForObject.name) = coolNameForObject;
But that syntax comes up bad on Dreamweaver. I've google-ed, but anything that comes up would be more easily solved via an array, and I'm confidant for what I need these objects for, being able to call up objects via property reference on a container object is the way to go.
I could skip the "addEntity()" entirely, and just go
Scene1.coolNameForObject = coolNameForObject;
But that seems to go against the idea of encapsulation.
Thank you.
Upvotes: 1
Views: 117
Reputation: 2077
Add property like this and make enumerable: true,this wiil not create problem. you can acess key easily.
Object.defineProperty(obj, "key", {
enumerable: true,
configurable: true,
writable: true,
});
Upvotes: 0
Reputation: 9530
Properties of Javascript objects can be added dynamically and named with the square bracket syntax either directly or from a variable:
var propName = "foo";
coolNameForObject[propName] = 'coolNameForObject';
coolNameForObject["bar"] = 'coolNameForObject';
Scene.prototype.addEntity = function(name, entity) {
this[name] = entity;
}
Upvotes: 1