Possible Duplicate:
Where is the “proper” place to initialize class variables in AS3
I was wondering if anyone knows wether its better to instantiate class on it’s variable declaration or within a constructor? For example, this:
protected var _errorHandler:ErrorHandler = new ErrorHandler();
or this:
protected var _errorHandler:ErrorHandler;
public function someClass() {
_errorHandler = new ErrorHandler();
}
A small point I think, but I want my code to robust and efficient as possible!
Thanks
Chris
Initialization in the constructor is preferred, for readability–for being able to easily see what gets initialized when. The least readable option would be to mix these, which I can’t recommend.
There is a third option that you will see AS3 programmers use:
This approach has two things to offer:
As far as performance goes, I believe your two examples would compile down to the same byte code. The AS3 compiler makes a special class initializer for static declarations that are outside the constructor, but for regular member variables initialized at declaration time, I expect it just moves the initializations to inside the constructor for you. But does it move them ahead or after what is explicitly in the contructor? I don’t remember, which is why I cite readability as a main reason to put everything in the constructor yourself 🙂