Wow - so today I figured out (after yelling for a short while) that Flash’s Actionscript 2 does not make copies of objects, it makes references. If you don’t know the difference you probably won’t benefit from this article, but here’s an analogy anyway. Consider this code:
var date1 = new Date(2007,0,1); // January 1, 2007 00:00:00
var date2 = date1;
var date2.setMonth(1); // February 1, 2007 00:00:00
If you’re anything like me you would expect date1
to still be January 1, 2007
and date2
to be February 1, 2007
- NOPE, WRONG! Stupid javascript tries to save RAM by automatically making references, or “pointers” (or “nicknames”) to Objects instead of copying them - this is not a real bad idea for javascript 1 I guess - since it’s a n00b language, but I can extend dynamic classes in AS2 - it’s an OOP language, so it should behave like one! So, since there’s no character to make a reference (in PHP you can use $date2 =& $date1), you can’t not make it a reference. To fix this problem I searched the net a bit and ran across an Object prototype that adds a clone() method to it. Unfortunately the clone method didn’t work for Date object, so naturally I was forced to make it work :(. Well, here it is - just paste this code somewhere in the beginning of your FLA or in an AS file that is included:
/*
************************************************************
Object.clone
by : Steve Kamerman (kamermans at teratechnologies.net)
Blog: http://www.teratechnologies.net/stevekamerman
Ver : 1.0
type: post
date: 13Jan2007
************************************************************
Object.clone creates a perfect copy of an object
Modified from R.Arul Kumaran's version to support Date Objects
*/
Object.prototype.clone = function() {
if (this instanceof Array) {
var to = [];
for (var i = 0; i<this.length; i++) {
to[ i] = (typeof (this[ i]) == "object") ? this[ i].clone() : this[ i];
}
}else if(this instanceof Date){
var to = new Date(this.getTime());
}else if (this instanceof XML || this instanceof MovieClip) {
// can't clone this so return null
var to = null;
trace("Object.clone won't work on MovieClip or XML");
} else {
var to = {};
for (var i in this) {
to[ i] = (typeof (this[i ]) == "object") ? this[ i].clone() : this[ i];
}
}
return(to);
}
ASSetPropFlags(Object.prototype, ["clone"], 1);
/*
Usage:-
var date1 = new Date(2007,0,1); // January 1, 2007 00:00:00
var date2 = date1.clone();
var date2.setMonth(1);
// now date2 contains the Date Object for February 1, 2007 00:00:00
// changing date2 will not affect date1
*/
I hope you like it!