Static initializers in AS3

Recently, several people have asked whether it’s possible to create some kind of constructor for static classes in ActionScript 3, and the answer is: yes!

The solution isĀ  a static initializer. This is a block of code, surrounded by curly brackets but no function or var declaration, that runs the first time a property or method of a static class is called. Static initializers are called before any property value is returned or function executed, in the same way a constructor always runs before you can access the properties or methods or a regular class.

package
{
    public class MyStaticClass
    {
        // This is the static initializer
        {
            trace("Running static initilizer!");
            staticInitializer();
        }
        
        // We're calling a secondary method so we can use local variables
        static private function staticInitializer():void
        {
            var now:Date = new Date;
            baseColor = now.hours > 16 ? 0x000066 : 0x0000FF;
        }

        static public var baseColor:uint;
    }
}

Although it’s not strictly necessary to call a secondary method, Flash Player will throw an error if you declare local variables within the static initializer itself.

To prove that the static initializer is running first, simple trace out the baseColor property:

trace(MyStaticClass.baseColor);

If it’s after 4pm, this will result in the following output in the console window:

Running the static initializer!
102