views:

980

answers:

3

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?

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

Usage

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

y = x.copy()

y[0] = 0

y[3][0]="d"

trace(x)

trace(y)
jerebear
This is a terrible solution, any object just bit complex would not be copied properly. Furthermore adding to the Object prototype is not good practice. I would even go as far as to say adding anything to the protype is bad practice. It's more a left over relic than a feature.
Lillemanden
+2  A: 

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!

BushyMark
+2  A: 
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()

maclema