0

Below is the snippet of the code. Basically, 'this.leaves' is a array. And I want to shift first array element, make copy of it (called frontLeaf), and unshift it to the original array, change some attributes from copied element, and put that element to the parent array element.

var frontLeaf = this.leaves.shift();
this.leaves.unshift(frontLeaf);
frontLeaf.leftChild = tmp;
frontLeaf.rightChild = this;
this.parent.leaves.push(frontLeaf);

My problem is that frontLeaf seems to be passed by reference that when I assign

frontLeaf.leftChild = tmp; 
frontLeaf.rightChild = this;

above two lines of code seems to affect both elements in this.leaves and this.parent.leaves... So, How can I resolve this problem?

user482594
  • 16,878
  • 21
  • 72
  • 108

3 Answers3

0

Here's what I did when faced the same issue:

var newObj = JSON.parse(JSON.stringify(oldObj));
taralex
  • 935
  • 2
  • 12
  • 29
0

Yes, in JavaScript objects are always passed by reference. If you want a copy of an object, you'll have to write a deep-copy routine yourself.

I'm not sure exactly what you're trying to do (what is tmp? what is this? what is this.leaves an array of?), but maybe there is a way to do it without needing a copy?

Brad
  • 603
  • 4
  • 12
0

Javascript passes all objects by reference. The only way to do what you're looking for is to create an entirely new object, do a deep copy and then push it.

See this post for a sample solution using jQuery.

Community
  • 1
  • 1
Demian Brecht
  • 21,135
  • 5
  • 42
  • 46