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

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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值