ActionScriptのスタティックイニシャライザ

AS3.0のスタティックイニシャライザの挙動が、Javaとちょっと違うことに気づいたのでメモ。

Javaの場合

Javaの場合は、スタティックフィールドイニシャライザも、スタティックイニシャライザも、定義された順番に実行される。

public class StaticInitializer { 
    public static String str1 = "hoge"; 
    public static String str2 = "dummy"; 

    static { 
        System.out.println("(StaticInitializer) str2=" + str2); 
        str2 = "Hello, " + str1; 
    }
    public static String str3 = str2; 
    
    public static void main(String[] args) { 
        System.out.println("str1 = " + StaticInitializer.str1); 
        System.out.println("str2 = " + StaticInitializer.str2); 
        System.out.println("str3 = " + StaticInitializer.str3); 
    } 
}

(結果)
(StaticInitializer) str2=dummy
str1 = hoge
str2 = Hello, hoge
str3 = Hello, hoge

ActionScript 3.0の場合

ActionScriptの場合は、先にフィールドのイニシャライザが実行され、その後でスタティックイニシャライザが実行されているみたい。

package
{ 
    public class StaticInitializer 
    {
        public static var str1:String = "hoge";
        public static var str2:String = "dummy";
        
        {
            trace("(StaticInitializer) str2=" + str2); 
            str2 = "Hello, " + str1; 
        }
        public static var str3:String = str2;

        public function StaticInitializer() {} 
    }
}
<?xml version="1.0" encoding="utf-8"?> 
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"> 
    <mx:Script> 
    <![CDATA[ 
        public function dump():void 
        {
            trace('str1 = ' + StaticInitializer.str1); 
            trace('str2 = ' + StaticInitializer.str2); 
            trace('str3 = ' + StaticInitializer.str3); 
        } 
    ]]>
    </mx:Script> 
    <mx:Button x="10" y="10" label="ボタン" click="dump()"/> 
</mx:Application>

(結果)
(StaticInitializer) str2=dummy
str1 = hoge
str2 = Hello, hoge
str3 = dummy