【问题标题】:Storing Javascript Objects in Another Object Dynamically将 Javascript 对象动态存储在另一个对象中
【发布时间】:2013-03-15 04:14:34
【问题描述】:

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

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 object methods


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-09-16
        • 2017-01-19
        • 2023-03-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多