9

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

        }

    }

}
Amarghosh
  • 58,710
  • 11
  • 92
  • 121
minimalpop
  • 6,997
  • 13
  • 68
  • 80

4 Answers4

16

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
  • 2,689
  • 26
  • 25
  • 1
    indeed, if you have any significant code put it in a function that gets called by the constructor. – Allan Oct 31 '09 at 01:29
6

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
  • 6,205
  • 4
  • 26
  • 33
3

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
  • 27,016
  • 6
  • 49
  • 73
2

Programmers new to AS3 often have problems referencing the stage (the well known 'it's not there' situation).

By doing ... :

public function ClassName()
{
    super();
    addEventListener( Event.ADDED_TO_STAGE, init, false, 0, true );
}

private function init( event : Event ) : void
{
    removeEventListener( Event.ADDED_TO_STAGE, init );
    // Reference stage.stageWidth;
    // Call init after some sort of load completion initialized in the constructor
}

... it's easily fixed.

Or sometimes you initialize an XML loader in the constructor, and then call the initialize function upon load completion.