views:

1501

answers:

3

Is it possible to pass a parameter to a method ByRef (or out etc) in ActionScript 3?

I have some globally scoped variables at the top of my class and my method will populate that variable if it's == null.

I'm passing in the variable which needs to be populated but so far my efforts have returned a locally populated variable leaving the globally scoped version of it still null.

The variable being passed to my method varies so I can't hardcode it in my method and simply set it.

+1  A: 

AS3 does not have pass by reference (it is similar to Java in this regard, in that it passes references by value).

Something similar can be simulated if you control the client code by wrapping the object in another object:

var myObj = null;
myFun({ a: myObj });
function (param) {
  if (param.a == null) {
    param.a = "Hello";
  }
}
jsight
+3  A: 

ActionScript 3 passes params by reference by default, like Java - except for primitive types. But what you are trying to have it do isn't passing by reference. The parameter passed in is a reference to an object(in the case when it's not a primitive type), which you may well modify inside of the function.

But, to answer your question. Here is a solution:

function populateIfNull(variableName, value){
    this[variableName] = this[variableName] || value
}

Which you can use like:

populateIfNull('name', 'Bob')
populateIfNull('age', 20)
toby
A: 

Use objects.

eg:

var myObj : Object = new Object(); var myArr : Array;

myObj.arr = myArr;

function populateViaRef(obj : Object) : void { obj.arr = new Array();

for(var i : Number = 0; i < 10; i++) obj.arr[i] = i;

}

populateViaRef(myObj);

for(var i : Number = 0; i < 10; i++) trace(myObj.arr[i]);

Razvan