javascript: private members and read-only properties

南楼画角 提交于 2019-12-06 15:21:25

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

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;
}

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/...

yourdeveloperfriend

See this answer.

this.get = function() {
   return jQuery.extend({}, collection);
});

In javascript, object should be pass by reference instead of pass by value. So, there is a referencing. You would modify the get function as below to serialize the object to JSON string and then deserialize it back to object to clone an object. JSON.stringify and JSON.parse is supported in all browsers without any 3rd party library.

this.get = function(){
 var s = JSON.stringify(collection);
 return JSON.parse(s);
}

If you have included jquery in your web site, you would make use of the $.extend function.
Reference : http://api.jquery.com/jQuery.extend/

this.get = function(){
 return $.extend({}, collection);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!