views:

1143

answers:

3

I have often seen an init() within the constructor of AS3 classes, sometimes even being the only code in the constructor. Why would it be useful to do this, if you could simply use the constructor function itself to initialize a class?

package 
{

    import flash.display.Sprite;

    public class Example extends Sprite
    {

        public function Example()
        {
            init();                 
        }

        public function init ( ):void
        {

         //initialize here

        }

    }

}
+6  A: 

In ActionScript 3, constructor code is always interpreted rather than compiled. I believe moving the code into an init() function may allow it to be compiled and optimized.

http://blog.pixelbreaker.com/flash/as30-jit-vs-interpreted/

John Lemberger
indeed, if you have any significant code put it in a function that gets called by the constructor.
Allan
I was not aware of that, interesting tidbit to know, thanks!
JStriedl
+3  A: 

The reason I have done it is so that I can re-initialize a class without creating a new instance of it. The init() method works as basically a "reset" button then, if you code it right, allowing you to return the class to its initial state while, for instance, allowing any variables that have been set to remain set.

Depending on how you code it, of course.

Myk
+1  A: 

Another reason can be that you need a reference to the stage or a parent container and is too lazy to set up a ADDED_TO_STAGE listener. Then you would have instantiate the class first, add it to the container and then call init() once it's on the displaylist.

grapefrukt