初始化函数的目的目的、初始化、函数

2023-09-08 14:20:26 作者:。硪扪都還晓

我经常看到,只需要调用一个init()函数的构造函数。为什么要有一个init()函数,如果你可以把在init()函数的内容在构造函数?

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?

推荐答案

这是对象的构造函数被调用每个实例只有一次,而一个初始化功能可称为多次。请看下面的code:

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
  }
}

基本上全部由对象的初始化过程所需的信息可能不可用的构造运行的时间,并有可能成为在稍后的点(在上述的例子中,当 ID 属性设置)。因此,它是有道理的有一个单独的的init()的时候。

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.