Search code examples
flashactionscript-3scopeflash-cs3

Flash Action Script 3 variable scope not working


I want to pass some variables from one class to another, but the code below is not working.

package a {
  public class a {
    public var a_var:String;
    public var x_var:String;
    public function a() {
      var a_var = 'My name';
      var x_var = 'X string';
    }
    public function show_a():String {
      return a_var;
    }       
  }

  public class b {
    public function b() {
      var a_obj:a = new a();
      trace('trace' + a_obj.a_var); //is this wrong?
      trace(a_obj.show_a()); //is this possible? if so, what would be the output?
    }
  }  
}

When I try to pass a_var from class a to class b, a_obj.a_var returns a null value.

How can I do this?


Solution

  • In your class a constructor replace:

    public function a() {
        var a_var = 'My name';
        var x_var = 'X string'
    }
    

    with:

    public function a() {
        this.a_var = 'My name';
        this.x_var = 'X string'
    }
    

    Keyword var creates local variable in contructor so that variable get garbage collecteded after flow gets out of contructor.
    By using this you assign value to instance variable which is what you want in that case.