All Date Variables Modified When One Date Variable is Focus of Modific

I would greatly appreciate an explanation of why the following results in changes to all the date variables at the top of the following code. I’ve tried many ways of finding out what is occurring, but I am stumped.

Thanks in advance!!!


set myDate to (current date)
set testDate to myDate
set testDate to my addMonths(testDate, 2)

set showDate to date string of myDate

on addMonths(modDate, theMonths)
	set totalMonths to ((month of modDate) + theMonths)
	if totalMonths > 12 then
		set excessMonths to totalMonths - (totalMonths div 12)
		set modDate's year to (totalMonths div 12)
		set modDate's month to excessMonths
	else
		set modDate's month to totalMonths
	end if
	return modDate
end addMonths


Browser: Firefox 50.0
Operating System: Mac OS X (10.10)

Hi.

When you pass a value to a handler, or set one variable to another, the variable which receives the value gets the very same object, not a copy. In other words, the date object in modDate is the same object as the one in testDate, which is the same one as in myDate. If you change the value of any of the object’s properties, you’ll see the effect whichever variable you use to look at it.

If you don’t want this to happen, you should make a copy.

copy myDate to testDate -- Not set testDate to myDate.

Or you could do it in the handler:

on addMonths(modDate, theMonths)
	copy modDate to modDate -- Set the variable to a different copy of the date object.

Thank you Nigel! I appreciate the insight! Works like a charm…