Sunday, August 17, 2008

Another Javascript feature

Javascript uses pointers when assigning objects. This can lead to unexpected results for those who are used to work with LotusScript and Visual Basic, where data is copied to the new object and is no longer connected to the original object.

In the example below note that date2 object was not deliberately changed after it was initially set, but still at the end of the script it gets a new value which is the same as the changed date1 object.

<script>
var date1=new Date();
var date2=date1;

alert(date2); //shows Sun Aug 17 11:46:50 UTC+0200 2008

date1.setMonth(5);
date1.setDate(9);


alert(date2); //shows Mon Jun 9 11:46:50 UTC+0200 2008
</script>

run example

It also works in the opposite direction: if you change date2, the date1 will also be changed.

2 comments:

Anonymous said...

Personally, I don't have a problem with the way JavaScript assigns objects and variables (I'm sure there's a good reason), but I partially agree with you -- I would at least like the option of sometimes assigning by value instead of reference.

Peptide Synthesis said...

Thanks for providing such a great Information, you can see