javascript:私有成员和只读属性 [英] javascript: private members and read-only properties

查看:128
本文介绍了javascript:私有成员和只读属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

场景

我有这个课程:

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}

问题

一切正常。但是如果我这样做:

Everything works right. But if I do this:

(myAssoc.get())[10] = {};
console.log(myAssoc.get());  //returns Object {10: Object, 12: Object, 14: Object}!!

私人会员集合最终被修改。

the private member collection is eventually modified. That is unexpected (and unwanted!).


  • 有什么问题?

  • 如何使 get()返回集合成员的复制,而不是成员本身?

  • What is wrong?
  • How to make get() to return a copy of the collection member, and not the member itself?

编辑

问题。因此,克隆集合成员可以完成这项工作。在设计模式中是否有另一种方式来破坏私有成员和相关的只读属性?

I have read this question. So cloning the collection member could do the job. Is there in design patterns another way to mamage private members and the related read-only properties?

推荐答案

没有什么是错的,这应该是标准的JavaScript行为(我认为这与JS关闭的东西有关)。 :)

Nothing is wrong this should be standard Javascript behavior( i think it is related with this JS closure stuff). :)

你将不得不手动克隆对象(我想),如果你不想使用jQuery和东西...和浅的副本就足够了p>

You would have to Clone the Object manually(i think), if you dont want to use jQuery and stuff... and a shallow copy is enough

function clone(obj)
{
    var cloneObj = {};
    for(var prop in obj )
    {
        cloneObj [prop] = obj[prop];
    }
    return cloneObj;
}

对于DeepCopies和东西,你必须克隆这些属性或写一个函数,你可以附加到对象原型,并调用clone的属性等等....
在我看来,对于Deepcopies,它的优点更好地与jQuery一起去,如果你在你的页面中使用它更好/ Project /...

for DeepCopies and stuff you would have to clone those Properties or write a Function, which you could attach to the object prototype, and call clone on properties and so on.... In my opinion for Deepcopies its probaly better to go with jQuery, and even more so if you are using it in your Page/Project/...

这篇关于javascript:私有成员和只读属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆