AS3静态代码块的初始化使用方法

来源:互联网 发布:华为连不上移动数据 编辑:程序博客网 时间:2024/06/16 05:38

In a nutshell: A static initializer is executed whenever you do anything with that class. It's executedbefore whatever you wanted to do (e.g. calling the constructor or accessing a field). It's also only executed once.

Many moons ago I released some code which utilized a static initializer. That code worked fine back then, but recent versions of the Flex SDK compiler don't really like it. Well, to tell the truth I also didn't like it, because the construct I used was sorta ugly and, well, pretty wrong.

The hello world of static initializers looks like this:

//static (this comment isn't required, but I recommend using one){    trace('woo! static!');}

Declaring variables there or using loops doesn't work, however. Loops used to work, but the proper way to handle this is better anyways. All you need is an anonymous function which is invoked directly:

//static{    (function():void {        var i:int;        for (i = 0; i < 3; i++){            trace(foo + i);        }    }());}

AS3 has function scope just like JavaScript. This means the declared variables are available within the function they were declared. So, we can use some temporary objects/variables and they will be discarded as soon as we're done with this initialization stuff. They won't waste memory and they also won't clutter up this class' namespace.

A Complete Example

HelloStatic.as

package {    import flash.display.*;    public class HelloStatic extends Sprite {        //static        {            trace('hello');        }        public function HelloStatic():void {            trace('world');            trace(OtherClass.field);        }    }}

OtherClass.as

package {    public class OtherClass{        public static var field:String ='not initialized yet';        //static        {            field = 'initialized';        }    }}

Output:

helloworldinitialized

 

0 0
原创粉丝点击