[英]javascript object property has pointer to another property
I have this code, wich adds Node to array and then changes it, the firstNode
object is set in the init
function. 我有这段代码,将Node添加到数组,然后对其进行更改,在init
函数中设置了firstNode
对象。
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? 第二次调试返回"Michael"
但是为什么呢? It looks the firstNodeValues
has a pointer to the node items[10]
. 看起来firstNodeValues
有一个指向节点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. 我想,如果我设置FirstNodeValues
在firstTime
后来改变节点值则firstNodeValues
没有变化,并保持完全一样,我第一次设置它。
The reason your clone is changing when you change your data is this: 更改数据时克隆更改的原因是:
this.firstNodeValues = Node;
There, you are declaring firstNodeValues
to be a reference to Node
, not a copy . 在这里,您声明firstNodeValues
是对Node
的引用 ,而不是copy 。 So everything you change in firstNodeValues
, changes in Node
, and vice versa. 因此,您在firstNodeValues
中更改的所有内容,在Node
更改的firstNodeValues
,反之亦然。
You'll need to clone the object, like this: 您需要克隆对象,如下所示:
function clone(obj){
if(obj == null || typeof(obj) != 'object'){
return obj;
}
var temp = {};
for(var key in obj){
if(obj.hasOwnProperty(key))){
temp[key] = clone(obj[key]);
}
}
return temp;
}
Then, you can copy the node, like this: 然后,您可以复制节点,如下所示:
this.firstNodeValues = clone(Node);
This will make sure that this.firstNodeValues
isn't a reference to Node
, but a new object, with the same properties / values as Node
(So, a clone). 这将确保this.firstNodeValues
不是对Node
的引用,而是一个具有与Node
相同的属性/值的新对象(因此,是一个克隆)。
You might be interested in jQuery.extend() . 您可能对jQuery.extend()感兴趣。 So: 所以:
this.firstNodeValues = $.extend( {}, Node );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.