开发者

How do you stop javascript assigning objects by reference?

开发者 https://www.devze.com 2023-01-08 19:34 出处:网络
I\'m using the date.js library. Previous code: alert(incidentDate); var deadlineDate = incidentDate; deadlineDate.add(2).years();

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 referen开发者_开发技巧ce. 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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号