The lack of a bit-wise copy in AS3 and the workaround
For the most part people don’t really think too hard about passing arguments into a function in AS3. There isn’t any funny business like you would find low level languages like C++ where you have to manually specify whether that argument is an address, reference, or a bit-wise copy of what is being passed in. This is really a good thing because the less manual memory management you do in a language the less likely you are to creative gaping memory leaks in a project. However, there comes a time when you really need to do a bit-wise copy of an object in order to get a completely fresh copy. In the ActionScript realm I hear this often referred to as a “Deep Copy”. In any event, here’s a scenario and the subsequent solution.
You have a DataGrid that is binding to an ArrayCollection. You want to pass a select set of those items on to a command. In some cases the command doesn’t need to massage the data any further and perhaps does something as simple as sending it off to a remote service method to be stored in a database. However, assume that command is a “Duplicate” command that takes a set of items and saves them back to the disk. Once you pass the selected items in you want to append the string “_Duplicate” at the end so as to not confused these with the original instance. This is where the issue comes in. Since the default argument behavior in AS3 is pass by reference when you append “_Duplicate” it will append it back to the original item that your DataGrid is binding to and you will see “MyItem_Duplicate” in the list.
In this case what you want to do is send a new copy of the selected items that bear no relation to the original DataProvider so that they can be edited and written back to the disk. How do you do this you ask?
There just so happens to be a utility just for this sort of thing called ObjectUtil (mx.utils.ObjectUtil). So to get a fresh copy of your object in question do this:
var freshCopy:ArrayCollection = ArrayCollection( ObjectUtil.clone(dataProvider) );
Now you’re free to change this collection however you want and leave the original collection in tact. Where our Duplicate command is concerned we can now edit the names to append “_Duplicate” and write them back the disk without contaminating our original objects or having the controls that bind to them display the undesired changes as we make them.