我有這個類:
var AssocArray = function(){
var collection = new Object();
this.add = function(id, o){
collection[id] = o;
}
this.remove = function(id){
delete collection[id];
}
this.getById = function(id){
return collection[id];
}
this.get = function(){
var res = collection;
return res;
}
}
var myAssoc = new AssocArray();
myAssoc.add("11",{ "packageId": "11", "machineId": "1", "operationType": "Download"});
myAssoc.add("12",{ "packageId": "12", "machineId": "1", "operationType": "Download"});
myAssoc.add("14",{ "packageId": "14", "machineId": "1", "operationType": "Download" });
if(myAssoc.getById("20")) myAssoc.remove("20");
if(myAssoc.getById("11")) myAssoc.remove("11");
console.log(myAssoc.get()); //returns Object {12: Object, 14: Object}
問題
一切工作的權利。但是,如果我這樣做:
(myAssoc.get())[10] = {};
console.log(myAssoc.get()); //returns Object {10: Object, 12: Object, 14: Object}!!
私有成員collection
最終修改。這是意想不到的(並且不需要!)。
- 出了什麼問題?
- 如何使
get()
返回副本的collection
成員,而不是成員本身?
編輯
我已閱讀本question。因此克隆collection
會員可以完成這項工作。設計模式中是否存在另一種方式來隱藏私有成員和相關的只讀屬性?