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 -
/// 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()
_t[i] = this[i];
return _t;
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: