我有这个类:
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
会员可以完成这项工作。设计模式中是否存在另一种方式来隐藏私有成员和相关的只读属性?