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
- AS3静态代码块的初始化使用方法
- 初始化代码块与静态初始化代码块的区别?
- 静态代码块 初始化块 代码块的区别
- Java类的初始化 静态代码块
- 静态代码块、代码块、构造函数的初始化顺序
- 静态代码块与初始化代码块
- Java 静态变量、静态代码块初始化的时机
- 构造代码块与静态代码块(静态初始化块)
- Java中父类与子类的普通代码块,构造代码块,静态代码块 初始化
- Java中非静态代码块,静态代码块和构造方法的初始化顺序
- Java中静态代码块、非静态代码块以及构造函数的初始化顺序
- Java中静态代码块及对象的初始化顺序
- JAVA中静态代码块及对象的初始化顺序
- Java静态块的初始化
- Java初始化-静态代码块、实例化代码块和构造函数的区分
- 变量初始化,构造代码块,静态代码块,执行顺序
- 静态类、静态方法、静态代码块及初始化顺序
- java中类的静态代码块、构造代码块、构造方法、静态成员的初始化顺序详解
- Effective STL 读书笔记
- Android开发布局
- javascript 实现MD5加密
- android 调用 webService
- mysql in 子查询 效率慢 优化(转)
- AS3静态代码块的初始化使用方法
- 弗洛伊德变种算法计算最短路径
- c++的萃取技术
- Effective STL第一部分: 容器
- shell 计算字符串长度
- 2013年总结
- tab键的使用
- ORA-01659: unable to allocate MINEXTENTS beyond 10
- 投料退回数据卡在接口里,推送过去之后,该批次无法做任何操作,提示无可用数量