我有了項目類型和ID的JSON對象運行從字符串JavaScript對象,我需要創建新的對象如何在不使用eval()
var data = {
"items":[
{"type":"generator","id":"item_1","x":200,"y":200},
{"type":"battery","id":"item_2","x":50,"y":300},
{"type":"generator","id":"item_3","x":200,"y":280},
{"type":"battery","id":"item_4","x":100,"y":400}
]
};
,我需要在項目的每一項運行
jQuery.each(data.items, function(index,value) {
eval("var " + value.id + " = new " + value.type + "(" + (index + 1) + ");");
eval(value.id + ".id = '" + value.id + "';");
eval(value.id + ".draw(" + value.x + "," + value.y + ");")
});
這不是一個好習慣,但我還能做什麼?
我需要再有
像
item_1.moveto(300,700);
,但我總是得到ITEM_1是undefind
這是一個非常好的模式。是不是更好地移除registerType函數並將類型函數(即Generator等)直接移動到匿名函數中? (如果不在外面使用) – 2014-12-03 01:01:23
另外,如果在forEach中使用「this [itemData.id] = createItem(i + 1,itemData)」,則可以刪除itemsMap對象並直接調用「item_1」。 – 2014-12-03 01:06:57
@plbsam使用模塊模式可以認爲是,但是在forEach中使用'this'會污染全局名稱空間,所以它不是一個選項。您不想爲每個項目創建一個全局變量。 – plalx 2014-12-03 02:46:01