开发者

Actionscript pass by reference

开发者 https://www.devze.com 2023-01-16 06:17 出处:网络
package { import flash.display.Sprite; public class test1 extends Sprite { private var tmp:Object; public function test1() {
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 开发者_如何学Goget modified?


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();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消