您的位置:首页 > 编程语言

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

2014-01-26 13:47 288 查看
In a nutshell: A static initializer is executed whenever you do anything with that class. It's executed
before 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:

hello
world
initialized
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐