justinl
justinl

Reputation: 10548

Where is the "proper" place to initialize class variables in AS3

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 {
}

Upvotes: 3

Views: 1724

Answers (2)

Adam Harte
Adam Harte

Reputation: 10520

Personally I don't do either! I like to create an "init" function that initializes everything. That means if I need to reset the instance to its default, I can just call the init method at anytime.

Upvotes: 2

Billy Back Bedroom
Billy Back Bedroom

Reputation: 592

I personally recommend initialization inside the constructor for two reasons:

  1. You cannot initialize objects that depend on other var objects having already been created before construction.
  2. 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.

Upvotes: 3

Related Questions