问题
Is it "better" to initialize AS3 class variables in the class constructor? Or can I just initialize them to their default value when I declare them at the top of my class? I ask because when there's a lot of class variables, it appears inefficient to declare them in one place and then initialize them in another when I could easily do both in the same place. It one option is better than the other, why?
Thanks!
eg:
initializing in constructor
class foo {
var bar:Boolean
}
function foo():void {
bar = true;
}
OR
initializing with the declaration
class foo {
var bar:Boolean = true;
}
function foo():void {
}
回答1:
I personally recommend initialization inside the constructor for two reasons:
- You cannot initialize objects that depend on other var objects having already been created before construction.
- It's easier to locate and understand initialization code when it's properly procedural. Especially when you (I) dive back into big classes I haven't opened for months.
回答2:
Personally I don't do either. I like to create an init function that initializes everything. That means if need to reset the an instance to its default, I can just call the init method at anytime.
来源:https://stackoverflow.com/questions/3105081/where-is-the-proper-place-to-initialize-class-variables-in-as3