1

这就是我想要完成的事情。我正在动态创建对象,并且想将它们添加到“主容器”对象中。我目前正在将数组用于容器,但有时我想按名称而不是按索引访问这些对象。如:

function Scene() {
     this.properties;
}

Scene.prototype.addEntity = function(entity) {
    this.push(entity);
}


var coolNameForObject = { Params };
var Scene1 = new Scene();

Scene1.addEntity(coolNameForObject);

我知道 .push 不可用,仅适用于数组,但我厌倦了整天使用索引。我想通过名称来引用每个实体。例如:

Scene1.coolNameForObject.property

但是想不出好办法。

也许有类似的东西:

coolNameForObject.name = 'coolNameForObject';
Scene1.(coolNameForObject.name) = coolNameForObject;

但这种语法在 Dreamweaver 上很糟糕。我已经用谷歌搜索过了,但是任何出现的问题都可以通过数组更容易地解决,而且我对我需要这些对象的用途很有信心,能够通过容器对象上的属性引用调用对象是一种方式去。

我可以完全跳过“addEntity()”,然后去

Scene1.coolNameForObject = coolNameForObject;

但这似乎与封装的想法背道而驰。

谢谢你。

4

2 回答 2

1

Javascript 对象的属性可以直接或从变量中动态添加并使用方括号语法命名:

var propName = "foo";
coolNameForObject[propName] = 'coolNameForObject';

coolNameForObject["bar"] = 'coolNameForObject';

Scene.prototype.addEntity = function(name, entity) {
    this[name] = entity;
}
于 2013-03-15T04:21:55.830 回答
0

添加这样的属性并使 enumerable: true,这不会产生问题。您可以轻松访问密钥。

 Object.defineProperty(obj, "key", {
  enumerable: true,
  configurable: true,
  writable: true,
 });
于 2013-03-15T04:27:38.417 回答