2013-03-15 103 views
1

這是我正在努力完成的。我動態創建對象,我想將它們添加到「主容器」對象。我目前正在使用容器的數組,但有時我想通過名稱而不是索引來訪問這些對象。如:動態地將JavaScript對象存儲在另一個對象中

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對象

回答

1

屬性可以動態添加,並與方括號語法直接或從一個變量命名爲:

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

coolNameForObject["bar"] = 'coolNameForObject'; 

Scene.prototype.addEntity = function(name, entity) { 
    this[name] = entity; 
} 
+0

非常好!這似乎工作,非常感謝你! – 2013-03-15 04:24:03

0

添加屬性像這樣,使枚舉:真的,這不是wiil創建問題。 您可以輕鬆獲取密鑰。

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