Pass by value

Actionscript 3 will always pass by reference unless the assignation is a primitive type (such as integer or string). I had an array and want to pass it by value (means it will copy the whole array’s value in it instead of referencing). It is because referencing will affect the referenced array when the new array is being changed in value.I came across with a script to deal with it. it may not be perfect, but have a look:

1
2
3
4
5
6
public function clone(source:Object):*{
  var myBA:ByteArray = new ByteArray();
  myBA.writeObject(source);
  myBA.position = 0;
  return(myBA.readObject());
}

Be aware that your objects in your array (or object)’s type may changed to Object/Array instead of it’s previous type.


Posted by Alan Cheung  September 20th, 2007

One Response to “Pass by value”

  1. geoff Says:

    Just use ObjectUtils.copy

    var myArray: Array = new Array();
    myArray.push(1);
    myArray.push(2);
    myArray.push(3);

    var myCopy: Array = ObjectUtils.copy(myArray) as Array;
    myArray.splice(0, 3);

    trace(myArray.length);
    trace(myCopy.length);

Leave a Reply