动态地在另一个对象中存储Javascript对象

Storing Javascript Objects in Another Object Dynamically

本文关键字:存储 Javascript 对象 一个对象 动态      更新时间:2023-09-26

这是我想要完成的。我正在动态创建对象,我想将它们添加到"主容器"对象中。我目前在容器中使用数组,但有时我想通过名称而不是通过索引访问这些对象。如:

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;

但是这似乎违背了封装的思想。

谢谢。

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

var propName = "foo";
coolNameForObject[propName] = 'coolNameForObject';
coolNameForObject["bar"] = 'coolNameForObject';
Scene.prototype.addEntity = function(name, entity) {
    this[name] = entity;
}

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

 Object.defineProperty(obj, "key", {
  enumerable: true,
  configurable: true,
  writable: true,
 });