-2

https://jsfiddle.net/meeky333/zhgybqou/8/

In my jsfiddle I have a 1st, 2nd and 3rd date. I have assigned 1 = new Date() and then assigned 2 = 1 and then 3 = 2, except I set the hours of 2 using .setHours().

I understand that .setHours() will not only return the date in an int form. But it will update the object it came from... But it has come from mySecondDate. So why is myFirstDate being changed also?

How do I make myThirdDate stay the same but keep the value of myFirstDate the same as it was.

NOTE: mySecondDate is just a throw away variable, It was just for illustration purposes.

Meeky333
  • 75
  • 6
  • 1
    `a = b` does not *clone* an object. Just sets a second variable pointing at the same object. – VLAZ Nov 22 '22 at 10:15
  • I find that odd that it does that. Makes sense though. Is there a general way to clone a variable? – Meeky333 Nov 22 '22 at 13:55
  • No, no general way. Dates are cloned via the constructor `newDate = new Date(oldDate)` but other objects might or might not have a copy constructor. They might or might not expose a way to clone. [`structuredClone`](https://developer.mozilla.org/en-US/docs/Web/API/structuredClone) can work for some objects but not all objects. For example it will clone a Date, also a plain object like `{a: 1, b: true, c: "hello"}` but it will not clone any functions, e.g. `{name: "fred", getName: function() { return this.name } }` will fail. – VLAZ Nov 24 '22 at 08:19

1 Answers1

1

They are pointing all to the same Object. You could copy the date like this:

var myControlDate = new Date();
var myFirstDate = new Date();
var mySecondDate = new Date(myFirstDate);
var myThirdDate = new Date(mySecondDate.setHours(3, 3, 3, 3));


console.log("myControlDate: " + myControlDate);
console.log("myFirstDate: " + myFirstDate);
console.log("mySecondDate: " + mySecondDate);
console.log("myThirdDate: " + myThirdDate);

I hope this helps.

  • This is helpful. It's a good way to fix my issue. So instead of assigning my variable another variable. I can create a new Date that just has the same values as my first Date(). Very clever. Thank you :) – Meeky333 Nov 22 '22 at 13:56