I have this code, wich adds Node to array and then changes it, the firstNode object is set in the init function.
var myClass = function() {
this.items = []
this.firstNodeValues = {};
this.init = function() {
var firstIndex = false;
for (i = 10; i <= 15; i++) {
Node = {};
Node.index = i;
Node.name = "undefined";
if (i == 10) {
Node.name = "John"
this.firstNodeValues = Node;
}
this.items[i] = Node;
}
}
this.iterate = function() {
var newIndex = 10;
for (i = 10; i <= 15; i++) {
this.items[i].index = newIndex;
if (i == 10) {
this.items[i].name = "Michael";
}
newIndex++;
}
}
}
var test = new myClass();
test.init();
console.debug(test.firstNodeValues.name) // this gives value "John"
test.iterate();
console.debug(test.firstNodeValues.name) // this gives value "Michael"
The second debug returns "Michael" but why? It looks the firstNodeValues has a pointer to the node items[10].
I want that if I set the FirstNodeValues in firstTime and later a change Node values then the firstNodeValues is not Changes and stay exactly the same as I first set it.
The reason your clone is changing when you change your data is this:
There, you are declaring
firstNodeValuesto be a reference toNode, not a copy. So everything you change infirstNodeValues, changes inNode, and vice versa.You’ll need to clone the object, like this:
Then, you can copy the node, like this:
This will make sure that
this.firstNodeValuesisn’t a reference toNode, but a new object, with the same properties / values asNode(So, a clone).