I often see constructor functions that just call an init() function. Why have an init() function if you can just put the contents of the init() function in the constructor?
-
1possible duplicate of [actionscript 3 init()](http://stackoverflow.com/questions/1650714/actionscript-3-init) – taskinoor Feb 01 '11 at 14:32
2 Answers
An object's constructor is called only once per instance, whereas an "init" function may be called multiple times. Consider the following code:
public class Foo
{
private var initialized:Boolean = false;
public function Foo(id:String = null)
{
_id = id;
if (id)
init();
}
private var _id:String = null;
public function get id():String
{
return _id;
}
public function set id(value:String):void
{
if (_id != value) {
_id = value;
init();
}
}
private function init():void
{
if (initialized)
return;
if (!id)
return;
initialized = true;
// do initialization here
}
}
Basically all the information required by the initialization process of the object may not be available at the time the constructor is run, and it may become available at a later point (in the above example, when the id
property is set). So it makes sense to have a separate init()
sometimes.

- 3,472
- 1
- 17
- 16
+1 @mj: some vars may not be avaible when the constructor is called.
a rather frequent config goes as follow:
package
{
import flash.display.Sprite;
import flash.events.Event;
public class Main extends Sprite
{
public function Main():void
{
if (stage) init();//if stage is available, init()
else addEventListener(Event.ADDED_TO_STAGE, init);//otherwise, wait for the stage to be available
}
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
//here we can access the stage
//stage.prop = value;
}
}
}
if this is the Main class ( or document class ), the stage will indeed be avaible in the constructor. we can immediately call init(). if this class is instantiated by another class, it won't be able to access the stage from the constructor: it will have to wait to be added to the stage before.
init() can bear another name btw: setup, reset... whatever, it's just a informal "convention" ; at least when you see an init function somewhere, you can be almost sure that it will initialize the object once all the necessary data are ready :)

- 1,067
- 6
- 9
-
-
1Another case of methods like these are when you use a specific framework that needs an instantiated (ie constructed) object, but waits a while before the instance should actually do something. In these cases the `init` name may vary. For example PureMVC and RobotLegs have an `onRegister` method, where initalization often takes place. Personally, I don't like the name `init` and would rather give these initalizers a more descriptive name. `setupStageListeners` for example. – epologee Feb 01 '11 at 16:15