as3 class constructor sequence dependent
filed in Flash as on Nov.19, 2009
1, if the constructor does not show that the super, will automatically call the super constructor beginning of the parent structure.
package
(
public class Father
(
public function Father ()
(
trace ( “parent structure”);
)
)
)
package
(
public class Son extends Father
(
public function Son ()
(
trace ( “sub-structure”);
)
)
)
Call the new Son, Output:
Parent structure
Sub-structure
2, super parent structure is not necessarily on the beginning of the constructor.
If the parent constructor may be called in some sub-class covers methods, while the sub-class of some variables of the method is initialized in the constructor, and could be considered super move to the tail of the implementation of the constructor.
package
(
public class Father
(
private var _width: Number;
public function Father ()
(
trace ( “parent structure”);
width = 10;
)
protected function set width (value: Number): void
(
_width = value;
)
)
)
package
(
import flash.text.TextField;
public class Son extends Father
(
private var txt: TextField;
public function Son ()
(
trace ( “sub-structure”);
txt = new TextField ();
/ / super ();
)
protected override function set width (value: Number): void
(
super.width = value;
txt.width = value;
)
)
)
Call the new Son, an error message:
TypeError: Error # 1009: can not access null object reference properties or methods.
at Son / set width ()
at Father ()
at Son ()
And the super () before the note Gurkha out, run ok.
3, if the class in the definition of member variables define the initial values, these members will precede the definition of variables in the statement that the implementation of the constructor.
Consider if the child class inherits the parent class, a member variable to the constructor in the constructor of the variable re-assignment, if we happen to declare the parent class definition of the variable to the initial value, and the sub-class re-assignment after the Call the parent constructor, the result will be beyond your desire.
package
(
public class Father
(
protected var _name: String = “father”;
public function Father ()
(
)
)
)
package
(
public class Son extends Father
(
public function Son ()
(
_name = “son”;
trace (_name);
super ();
trace (_name);
)
)
)
Call the new Son, the output
son
father
Leave a Reply