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
}
}
}
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/
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With