问题
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?
回答1:
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.
回答2:
+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 :)
来源:https://stackoverflow.com/questions/4863706/purpose-of-init-function