an AS3 class cannot pass a MovieClip as a parameter to its super class...?
Is there a reason why it can't work??
Here is a code sample :
main.as
package{
import flash.display.MovieClip;
public class main extends MovieClip{
public function main(){
addChild(new Square());
}
}
}
Square.as (Which is a linked MovieClip that have a MovieCli开发者_Go百科p called "submc" on its timeline)
package{
import flash.display.MovieClip;
public class Square extends SuperSquare{
public var submc:MovieClip;
public function Square(){
super(submc, 1234);
trace("submc : " + submc);
}
}
}
SuperSquare.as
package{
import flash.display.MovieClip;
public class SuperSquare extends MovieClip{
public function SuperSquare(_p:MovieClip, _value:Number){
trace("_p : " + _p + " _value : " + _value);
}
}
}
When running this code, it traces :
_p : null _value : 1234
submc : [object MovieClip]
The "submc" property can't get through Square super constructor. I probably missed something? Any advice?
Thanks
Old Answer You have to initialize submc. The body of the Square class should look like this:
public var submc:MovieClip;
public function Square()
{
submc = new MovieClip();
super(submc, 1234);
trace("submc : " + submc);
}
The variable submc is null until you either initialize it or make it reference some other instantiated object.
New Answer If you are referencing elements on the timeline you may need to wait until the parent elements have been added to the stage before you reference nested elements. To do this you can either add an event listener for ENTER_FRAME or ADDED_TO_STAGE.
package{
import flash.display.MovieClip;
public class Square extends SuperSquare
{
public var submc:MovieClip;
public function Square()
{
// -- either one of these should work
addEventListener( Event.ADDED_TO_STAGE, onAdded );
addEventListener( Event.ENTER_FRAME, validateStage );
}
}
public function onAdded( event:Event ):void
{
// -- creates a problem because you can only call a super constructor in a constructor
// super(submc, 1234);
trace("submc : " + submc);
}
public function validateStage( event:Event ):void
{
if( !stage ) return;
if( stage.stageWidth == 0 ) return;
// -- ok to reference stage elements now
removeEventListener( Event.ENTER_FRAME, validateStage );
}
}
I'm not completely sure that this is your problem. However, I've seen similar problems with referencing stage elements too soon.
精彩评论