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]


}

3 Answers 3

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)
}

Sign up to request clarification or add additional context in comments.

3 Comments

thanks for pointing it out I will edit my answer
Thanks. I've never heard of spread syntax
0

You can use spread syntax for a shallow copy.

this.updatableData = [...data];

Or Array#slice:

this.updatableData = data.slice();

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.