设想
我有这门课:
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
而不是成员本身?
编辑
我读过这个问题。所以克隆collection
成员可以完成这项工作。设计模式中是否有另一种方法来管理私有成员和相关的只读属性?