在egret中,构造函数 constructor 在这个 test 类被实例化(new)时执行。
class test extends egret.Sprite{
public constructor() {
}
}
而在一些情况下,需要在初始化时对类的属性进行设定,有时会需要用到
// 当前类的舞台宽度
this.stage.stageWidth
// 当前类的舞台高度
this.stage.stageHeight
来设定Sprite的位置,如果把这些直接写在构造函数或者构造函数调用的方法里,系统会报错,原因是这个元素还没有被添加到舞台上,所以获取不到舞台。
在写一个类时,会使用
class test extends egret.Sprite{
public constructor() {
super();
this.once(egret.Event.ADDED_TO_STAGE,this.init,this);
this.once(egret.Event.REMOVED_FROM_STAGE,this.destroy,this);
}
private init (){}
private destroy (){}
}
将需要初始化的东西写在 init 函数里,在将显示对象直接添加到舞台显示列表或将包含显示对象的子树添加至舞台显示列表中时(addChild)调度,回调 init 函数。
在对象被删除显示(removeChild)时做的事情(清除事件,清除动作等)写在 destroy 里,在从显示列表中直接删除显示对象或删除包含显示对象的子树时调度,回调 destroy 函数。