views:

73

answers:

1
package {
    import flash.display.Sprite;

public class test1 extends Sprite {

private var tmp:Object;

public function test1() {
  createObj(tmp);
  if(tmp == null) {
    trace("nothing changed");
  }
}

private function createObj(obj:Object):void {
  obj = new Object();
}

}
}

In the above code the output on the console is :
nothing changed

Why?

If the argument to createObj was passed by reference(which is the
default behavior of actionscript), why did it not get modified?

+3  A: 

You don't pass a reference. You are passing null which is assigned to the local variable obj for use within the function.

Passing arguments by value or by reference:

To be passed by reference means that only a reference to the argument is passed instead of the actual value. No copy of the actual argument is made. Instead, a reference to the variable passed as an argument is created and assigned to a local variable for use within the function.

In createObj you are creating a new reference which you must return:

public function test1() {
  tmp = createObj();
  if(tmp != null) {
    trace("Hello World!");
  }
}

private function createObj():Object {
  return new Object();
}
splash
@splash. Your answer solves the problem of the OP, but I though I'd add that `null` doesn't really change how things work here. It's a shame the docs are so poorly written. That whole paragraph in the docs is a royal mess and hardly makes any sense. AS stores references to objects in variables (or parameters). A reference is a "link" to an object, not the object itself. References are *copied* when passed to a function; so they're passed *by value*. AS has pass by value semantics (that's why you can't implement the classic "swap" example in AS directly). *AS passes references by value*.
Juan Pablo Califano
PS. Here's a good article that explains the difference between passing by reference and passing a reference by value: http://javadude.com/articles/passbyvalue.htm. It's about Java but it applies to Actionscript as well.
Juan Pablo Califano