Pass by Value

5.04.2010

POSTED IN Programming | TAGS :

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:

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.

UPDATE: There is also a method in Flex ObjectUtil class called “copy” ObjectUtil.copy(); which copies the specified Object and returns a reference to the copy.

Hopefully this is helpful to someone.