Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
76
rated 0 times [  78] [ 2]  / answers: 1 / hits: 6685  / 10 Years ago, fri, july 4, 2014, 12:00:00

When i'm trying to know functionality of setDate() ,setTime() of javscript date i came across this problem.



<script>
var date1 = new Date();
var date2 = new Date(1991,4,11);
var date3 = new Date(1992,4,11);

date3 = date1;
date2 = date1;
date2.setDate(date2 .getDate() + 40);//im changing only date2 value using setDate()

//print values

</script>


I think the result will be like:

Fri Jul 04 2014

Wed Aug 13 2014

Fri Jul 04 2014



But in output all date variables have same value:



Wed Aug 13 2014



Wed Aug 13 2014



Wed Aug 13 2014



jsfiddle



If i do similar kind of code with integer variables they work like as i think(all int variables have different values).



Summary of Questions




  1. How date assignment and number assignment differs?

  2. Why and how javascript setDate() tracking other date variables?

  3. Last but not least What i have to do if i want to change only date2 value with these assignments?



Thanks in Advance.


More From » jquery

 Answers
0

You need to make a copy of your dates, like this:


date3 = new Date(date1.getTime());
date2 = new Date(date1.getTime());

or simply:


date3 = new Date(date1);
date2 = new Date(date1);

instead of


date3 = date1;
date2 = date1;

Otherwise, your variables all point to the same Date object (initially referenced by date1).




EDIT (about memory allocation)


    - Example 1:

var date1 = new Date();           // Memory allocation for an object
var date2 = new Date(1991,4,11); // Memory allocation n°2
var date3; // Obviously no memory allocation here

date3 = date1; // No memory allocation either, date2 and date3
date2 = date1; // become references of the object in date1

In this example, there are two memory allocations but only one of them is useful as the object in date2 is not used.


Note: The object that was originally in date2 still exists, but is not referenced anymore (it will be garbage-collected).




    - Example 2:

var date1 = new Date();            // Memory allocation for an object
var date2 = new Date(date1); // Memory allocation n°2
var date3 = new Date(date1); // Memory allocation n°3

In this example, there are three memory allocations for 3 different objects. The 2nd and 3rd allocations consist in creating new Date objects, containing a copy of the object in date1.




I hope it is clearer with this little explanation. If you're interested in memory management in JavaScript, I suggest you have a look at this:


https://developer.mozilla.org/en-US/docs/Web/JavaScript/Memory_Management


[#44125] Thursday, July 3, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
breonnamayah

Total Points: 574
Total Questions: 115
Total Answers: 96

Location: England
Member since Sun, May 21, 2023
1 Year ago
;