dev.e.loper
dev.e.loper

Reputation: 36044

Actionscript - how to pass object by value?

I want to pass an object to a function by value so that I can make modifications to that object. I don't want the original object to be updated. However, all the function parameters are passed by reference.

I've tried to copy an object ( var new_object:Object = original_object; ) This just creates a pointer to original_object.

Is there a way I can pass parameter by value?

update One workaround I see is to make deep copy of an object by using ByteArray as described here. Not sure how efficient it is. Maybe there is a better solution out there.

Upvotes: 1

Views: 496

Answers (1)

Barış Uşaklı
Barış Uşaklı

Reputation: 13532

You will have to make a copy of the object before passing it to the function :

public function copy(value:Object):Object
{
    var buffer:ByteArray = new ByteArray();
    buffer.writeObject(value);
    buffer.position = 0;
    var result:Object = buffer.readObject();
    return result;
}

public function testFunction(obj:Object):void
{  
   //do something with obj
}

public function test():void
{
  var obj:Object = {};
  testFunction(copy(obj));
}

Upvotes: 5

Related Questions