Action Script 3's static initializer
Actionscript 3 has a handy undocumented feature called
static initalizer's. These nifty little buggers allow you to execute code when a
class is loaded into memory, before any objects are initalised from the class. Unlike a constructor which is executed every time a object is initialised,
static initalizer's only execute once. This means they are perfect for the singleton pattern!
The
static initalizer's code is placed within a class, however like a namespace, class or method there are NO keywords describing it. Here's some basic code to show you how a static initalizer works.
package
{
class ExampleStaticInitalizer
{
public static const test:String = new ExampleStaticInitalizser('test');
private var test:Boolean = false;
private var value:String;
// start static initalizer
{
test = true;
}
// end static initalizer
public function ExampleStaticInitalizser(label:String)
{
if(test) {
throw new Error('unable to init');
}
value = label;
}
public function toString():String
{
return value;
}
}
}
The code above creates a enum object that you access though the static constant. The following code uses ExampleStaticInitalizer as the enum object.
var enum:ExampleStaticInitalizer = ExampleStaticInitalizer.test;However if you try to create a new instance of ExampleStaticInitalizer via:
var enum:ExampleStaticInitalizer = new ExampleStaticInitalizer();The runtime will throw an error!
I'll be posting an example later of a Enumerate package that will help you build Enumerate objects that parse various types of data (strings, numbers, objects).