Calling member functions before constructor
-
05-07-2021 - |
Question
In AS3, you can initialize a member variable (or constant) by calling a member function. This happens before the constructor is called. In the meantime, the 'this' keyword is perfectly accessible in the initializing member function even though the constructor function hasn't been issued yet.
This sounds like a time bomb. Can anyone comment on the above practice?
Edit :
...
private var member:Sprite = getSprite(); // called before constructor
...
private function getSprite():Sprite {
var spr:Sprite = new Sprite();
this.addChild(spr); // 'this' used before constructor
return spr;
}
Solution
As I understand it, that's fine (if not really nice and readable). What happens when new is called is:
- Memory is allocated for the instance (
this
becomes available) - All members are initialized (either to their default or whatever is specified)
- The constructor is called
new
returnsthis
The danger lies in that you have to make sure that nothing in getSprite()
requires something that is initialized in the constructor (including the parent constructor, if it's called). I would avoid it and just initialize everything in the constructor instead.
OTHER TIPS
You really just can't do what you're saying. You can't possibly access a non-static method on an instance if it hasn't yet been constructed. As to Jonatan's comment about the constructor calling super, this is implicitly done if you don't put a call to super() in your constructor body it automatically occurs at the top of the method. When you construct an object in an object oriented language you're allocating the memory for all the members of the class.
If you were to say:
var myVar:MyObject;
myVar.doSomething(); //this line creates a null pointer exception because myVar is null
If instead you were to say:
var myVar:MyObject = MyObject.createInstance(); // assuming createInstance is a static method that returns an instance of MyObject
myVar.doSomething(); //assuming createInstance() didn't return null then this works
But in this second case you can't reference "this" keyword from within the static method createInstance().
If you show a full example that refutes what I'm stating then I'll run it and delete my post, but I'm pretty sure I'm right here.