David Wolever
David Wolever

Reputation: 154594

ActionScript: what's the defined order for initializing internal/static/instance variables?

Consider a .as file which looks like this:

package foo {
class Foo {
    public static var a:* = getA();
    public static var b:* = getB();
    public var c:* = getC();

    public static function d():* { ... }

    public function Foo() {
        trace("initializing");
    }
}
}

// internal functions/variables
var e:* = getD();
function f():* { ... }

What is the defined order for initializing each of the variables/functions a..f?

(I know I can do experiments to find out… But I'm looking for the actual specified definition)

Upvotes: 1

Views: 740

Answers (1)

back2dos
back2dos

Reputation: 15623

Well, the tricky part is static initialization.

All static methods and variables are declared prior to any execution. Static methods are "instantly" initialized, in the sense that you can call them at any time. Then static variables are initialized in order of appearance. Then all static initialization is performed in order of appearence:

package {
    import flash.display.Sprite;
    public class Main extends Sprite {      
        __init(c,'static');//"static initialization b" because all variables are initialized prior to static initialization
        public static var a:String = __init(b);//"variable initialization null", because b is declared, but not initialized
        public static var b:String = __init('b');//"variable initialization b" for obvious reasons
        public static var c:String = __init(b);//"variable initialization b" because b is now initialized
        public static function __init(s:String, type:String = 'variable'):String {
            trace(type, 'initialization', s);
            return s;
        }
        public function Main():void {}      
    }
}

But in general, my advise is not rely on it, unless you really have to.

Upvotes: 2

Related Questions