Static Constructor / Initializer

package{
	
	public class Lookup{
		
		private static var _random:Array;
		// static initializer
		{
			trace("I am a static initializer for " + Lookup);
			init();
		}
		
		private static function init():void{
			 _random = new Array();
			 // generate some filler values
			 for (var i:int = 0; i<100; i++){
			 	_random.push(Math.random() * i);
			 }
		}
		
		public static function get random():Array{
			return _random.concat();
		}
	}
}

…and to test out the above class:

package {
	import flash.display.Sprite;

	public class Main extends Sprite{
		public function Main(){
           trace(Lookup.random[50]);
		}
	}
}
/*
outputs:
I am a static initializer for [class Lookup]
5.4258062043227255
*/

The above shows how to use static initializers. I’ve found this to be very handy… in this case we create an array of random values….

Tomorrow I’ll actually post a real class where I make use of this… the Lookup class in this case is really just filler code….

1 comment

Leave a Reply

Your email address will not be published. Required fields are marked *