1

I'm using the date.js library.

Previous code:

alert(incidentDate);
var deadlineDate = incidentDate;
deadlineDate.add(2).years();
alert(incidentDate);
return;

Adding to the deadlineDate caused the incidentDate to change too. A bit of reading revealed that this was because objects in javascript are always assigned by reference. I've found a workaround (below), but it's blooming messy. There must be some neater way to do this, surely?

And besides, the workaround I've used applies only to Date objects. How would I deal with another object type?

Current code:

var deadlineDate;
deadlineDate = incidentDate.toString('yyyy-MM-dd');
alert(incidentDate);
alert(deadlineDate);
deadlineDate = Date.parse(deadlineDate);
alert(incidentDate);
alert(deadlineDate);
deadlineDate.add(2).years();
alert(incidentDate);
alert(deadlineDate);
return;

Note: All the alerts are just for debugging.

TRiG
  • 10,148
  • 7
  • 57
  • 107
  • It's not that messy once you take out the alerts. And the generic answer is cloning, but it only works well for plain objects, not with specific types of objects. – Anurag Jul 21 '10 at 16:26
  • possible duplicate of [JavaScript: How to pass object by value?](http://stackoverflow.com/questions/7574054/javascript-how-to-pass-object-by-value) – Jim G. Dec 30 '14 at 03:35
  • Just FYI, alert works for very quick debugging but it really limits your abilities to debug and slows you down in the end. You should become familiar with the F12 developer tools window and `console.log`/`console.table`. You can output entire objects, multiple objects, and click through properties to see what is happening. – Marie May 04 '18 at 13:33

1 Answers1

0

As Anurag said, the only general solution is cloning. However, there's a better way to write your workaround. Use the millisecond value to create a new Date rather than formatting a string and then having to parse it.

Community
  • 1
  • 1
Matt Ball
  • 354,903
  • 100
  • 647
  • 710