Javascript - how to NOT assign by reference

Well consider this bit of code:

var d1 = new Date(); var d2 = d1; d2.setDate(d2.getDate()+1); alert(d1 + "\n" + d2); 

Even though I call setDate() on d2 , d1 also increments. I understand this because d1 is assigned to d2 by reference. My question is: how do I NOT do this, so that .setDate() only applies to d2 ?

+4
source share
3 answers

In JavaScript, all objects are assigned to variables by reference . You need to create a copy of the object; Date simplifies:

 var d2 = new Date(d1); 

This will create a new date object by copying the value of d1 .

+10
source

You need

 var d2 = new Date(d1.getTime()); 

See How to clone a Date object in JavaScript for more details.

+1
source

Think this should work:

 var d1 = new Date(); var d2 = new Date(); d2.setDate(d1.getDate()); d2.setDate(d2.getDate()+1); alert(d1 + "\n" + d2); 
0
source

Source: https://habr.com/ru/post/1394522/


All Articles