Max Blog

My Blog

Those funny declarations

When you declare a local variable in AS3 it turns out that it is visible for the hole scope it was declared in.
So for example you can declare a variable after its usage in code:

?View Code ACTIONSCRIPT
package {
  import flash.display.Sprite;
  public class Decl extends Sprite {
	public function Decl() {
	  trace(a);
	  var a : String = "hello";
	}
  }
}

But the assignment will be executed as “expected” after the trace and that’s why you see “null” traced in the console.

You can also make a duplicate declaration of a local variable, if it keeps the same type.

?View Code ACTIONSCRIPT
package {
  import flash.display.Sprite;
  public class Decl extends Sprite {
	public function Decl() {
  	  var a : String = "hello";
	  trace(a);
	  var a : String = "hello2";
	  trace(a);
	  // var a : int = 2; That would be bad!
	}
  }
}

Another interesting declaration behavior is the declaration of error variable in catch block:

?View Code ACTIONSCRIPT
package {
  import flash.display.Sprite;
  public class Decl extends Sprite {
	public function Decl() {
	  try{
		trace(a);
		a.length;
		// trace('error: ' + (error)); Invisible			
	  }catch(error:Error) {
		var a : String = "error";
		trace('a: ' + (a));
		trace('error: ' + (error));
	  }
	  trace(a);
	  // trace('error: ' + (error)); Invisible
	}
  }
}

So error is only visible in the catch scope but the catch scope is not really a scope because if we declare variable “a” in the scope itself it is visible in the whole method.

Last funny example is about for-loop and static initializer.

?View Code ACTIONSCRIPT
package {
  import flash.display.Sprite;
  public class Decl extends Sprite {
    static var array = [1,2];
    for (var i : int = 0;i < array.length;i++) {
      trace(array[i]);
    }
    public function Decl() {
      trace(i);
    }
  }
}

The problem with this code is that variable “i” is declared inside of class declaration and that means that it is a field. It also not declared with static modifier and that’s why you can’t use it in your static initializer code.

posted by admin in AS3 Creative point of view and have No Comments

Place your comment

Please fill your data and comment below.
Name
Email
Website
Your comment
Before you submit form:
Human test by Not Captcha