I've searched high and low without finding a solution. Why is it so difficult to clone a javascript object with private members without causing them to become quantum entangled?
Take a look at this code... It's a simple private property with getter and setter functions. For some reason, when I call the public setter on one instance, the cloned object also gets changed. How is this happening? Is there a way to fix it?
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
Any suggestions would be greatly appreciated.
Edit: So far, no luck. I understand that javascript doesn't follow traditional Object Oriented principles like Java or C++, but there must be a workaround. Even if it's not pretty, there has to be a way.
I understand.
Solution A: change this.changed instead of var changed
Solution B: create my own cloning function that recreates the entire object from scratch
I was hoping for a Solution C that could make javascript behave more like standard Object Oriented languages.
Can anyone help me out with something other than A or B?