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:

mdm-adph 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.

Anonymous said...

酒店打工

酒店兼職

台北酒店

打工兼差

酒店工作

酒店經紀

禮服酒店

酒店兼差

酒店上班

酒店PT

酒店

酒店喝酒

酒店消費

喝花酒

粉味

喝酒