Hi,
I've looked all around and found nothing to help me. Why on earth can't I clone a javascript object with private members without making them quantum entangled?
Just look at this code... It's a plain private property with getter and setter. Somehow if I call the public setter on one instance, the cloned one gets changed too. Why? Can it be worked around?
obj = function(){
var changed = 0;
this.getChanged = function(){
return changed;
}
this.setChanged = function(){
changed = 1;
}
this.setUnchanged = function(){
changed = 0;
}
};
myObj = new obj();
copiedObj = $.extend(true, {}, myObj); // Or any other deep copy function you'd have around
myObj.setChanged();
myObj.getChanged(); // returns 1
copiedObj.getChanged(); // returns 1!
copiedObj.setUnchanged();
copiedObj.getChanged(); // returns 0
myObj.getChanged(); // returns 0
Thanks for any ideas.
Edit: So far, nothing new. I know javascript doesn't really have OO like Java or C++, but hey we're talking about programming languages, there is always one way out. Sometimes it's ugly but there is one.
I get it.
Solution A: just make it this.changed instead of var changed
Solution B: make my own clone function that rebuilds the whole object anew
I was just hoping there would be some Solution C that would trick javascript into standard Object Oriented patterns.
Somebody, am I really stuck with A or B?