Actionscript – Variable Assignment without reference? – Education Career Blog

Should be easy. I have an object. I want to modify it, but before i do I want to save a copy of it that I can go back to. I tried setting copy = original but when i modify the attributes of the original the copy also shows the changes. I am assuming this is because in actionscript any time you assign, it really just stores a reference to the original object. So whats the best way for me to store a copy of the original object for later use?

,

var newObj:Object = Object(ObjectUtil.copy(oldObj));

“Copies the specified Object and returns a reference to the copy. The copy is made using a native serialization technique. This means that custom serialization will be respected during the copy.

This method is designed for copying data objects, such as elements of a collection. It is not intended for copying a UIComponent object, such as a TextInput control. If you want to create copies of specific UIComponent objects, you can create a subclass of the component and implement a clone() method, or other method to perform the copy.”

http://livedocs.adobe.com/flex/3/langref/mx/utils/ObjectUtil.html#copy()

,

What you are looking for is a deep copy of the object rather then passing by reference. I found the answer here which uses the new ByteArray class in AS3:

http://www.kirupa.com/forum/showthread.php?p=1897368

function clone(source:Object):* {
 var copier:ByteArray = new ByteArray();
 copier.writeObject(source);
 copier.position = 0;
 return(copier.readObject());

}

Which you then use like this:

newObjectCopy = clone(originalObject);

Cheers!

,

 // duplicate any given Object (not MCs)  
 Object.prototype.copy = function()  
 {  
     ASSetPropFlags(Object.prototype,"copy",1);  

     var _t = new this.__proto__.constructor(this) //

     for(var i in this){  
         _ti = thisi.copy()  
     }  
     return _t  
 };  

Usage

x = "1","2","3",4,5,{a:1,b:2}

y = x.copy()

y0 = 0

y30="d"

trace(x)

trace(y)

Leave a Comment