First of all let me introduce you the “Compilation Unit”. Compilation unit is the smallest code entity that can be compiled properly (to SWF file).
In ActionScript3 those entities are “as” or “mxml” files. (I skip “mxml” because it’s own topic )
The “as” files must be structured as following to become a compilation unit:
–Package declaration
— Class | Interface | Function | Variable | Constant | Namespace declaration
—- (if Interface) Method | Getter | Setter declaration
—- (if Class) Method | Getter | Setter | Constructor | Field | Constant | Namespace declaration
-Local Class | Interface | Function | Variable | Constant | Namespace declarations
So you need a package declaration with an element inside to make it a compilable entity
package { var a; } |
And you can hide declarations from anybody when you put them outside of package declaration
package { public const KingOfPop : Michael = new Michael(); } class Michael{ public function dance() : String { return "Moon Walk"; } } |
By the way this is the one and only good implementation of Singleton Pattern in AS3.
But it’s not what I want to show here. What I want to show is that my first definition of compilation unit was wrong because you can write statements between listed declaration and those will be executed as static initializer code.
So check this out:
package{ trace("A"); import flash.display.Sprite; trace("B"); class Test extends Sprite{ trace("C"); public function Test(){ trace("D"); } trace("E"); } trace("F") } trace("G") |
Can you tell what will be traced?
Last but not least conclusion – with this info in mind you can use AS3 as a “real” script language:
package{ import flash.display; class A extends Sprite} var a = 10; var b = 20; trace("a+b="+(a+b)); |