Wednesday 5 May 2010

Actionscript deep copy function

Here is an recursive function I found that allows you to deep-copy objects (other then MovieClips) in ActionScript. #ctionscript doesn't have this functionality built in yet, so this may prove useful to someone. Credit to the original poster - http://theolagendijk.wordpress.com/2006/09/04/actionscript-object-duplication/.
/// duplicate any given Object (not MCs)
Object.prototype.copy = function()
{
var _t = new this.__proto__.constructor(this) ;
for(var i in this)
{
if(typeof this[i] == “object”)
_t[i] = this[i].copy()
else
_t[i] = this[i];
}
return _t;
};
ASSetPropFlags(Object.prototype,["copy"],1);
This is very useful to me, as copying objects, usually arrays, is something that crops up often, at least for me ;). This way I can be sure that the contents get copied, not just the reference.

This is how it’s used.
var x:Array = new Array(“1″,”2″,”3″,{a:1,b:2});
var y:Array = x.copy();

No comments: