0

I am new to JS constructor functions. I have an object/constructor. The function takes data as a property. However I need two copies of the data: one to change and then one as a reference to reset to. However, changing one seems to change the other no matter what:

var myData = [1, 2, 3, 4, 5]
myFunction(myData)

function myFunction(data){
   this.updatableData = data;
   this.resetData = data;

   this.updatableData.pop()

   console.log(this.resetData)

   //expect [1,2,3,4,5]
   //but get [1,2,3,4]


}
auto
  • 1,062
  • 2
  • 17
  • 41

3 Answers3

1

use the spread syntax to make a copy of the original array

var myData = [1, 2, 3, 4, 5]
myFunction(myData)

function myFunction(data){
   this.updatableData = data;
   this.resetData = [...data];

   this.updatableData.pop()

   console.log(this.resetData)
}
nyarthan
  • 350
  • 2
  • 10
0

You can use spread syntax for a shallow copy.

this.updatableData = [...data];

Or Array#slice:

this.updatableData = data.slice();
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
0

That's called reference type.

When you change the reference, it affects all objects pointed to that address.

In good old javascript we used to copy arrays like this:

var arr = [1,2,3,4];
var arr_copy = [].concat(arr);

arr.pop(); // remove last item from the original array

console.log(arr) // prints [1,2,3]

console.log(arr_copy) // prints [1,2,3,4]

And this approach is still actual if you are looking for a cross-browser solution.

Ashot
  • 1,229
  • 1
  • 12
  • 13