开发者

Instantiate class on variable declaration or within constructor [duplicate]

This question already has answers here: Closed 11 years ago.

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 d开发者_如何学编程eclaration 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:

  • No initialization in the variable declarations
  • Empty (or nearly empty) constructor
  • All initialization done in one or more dedicated init() functions

This approach has two things to offer:

  1. You can easily reset the object for re-use by calling init again
  2. You can get around the limitation that AS3 does not let you overload the constructor like other similar languages (Java/C++/C#). You might want to, for example, be able to initialize a data structure with one or more different types of objects.

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 :-)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜