Search code examples
functionvariablesactionscriptconstructorparent

AS3: Trouble passing variables to child function


I recently changed the constructor functions of my display objects to verify they are on stage. However, this has completely broken my ability to pass values to child functions. For example (much code removed for clarity):

Parent:

public var var1:uint;
public var var2:uint;
public var childFunction:ChildFunction;

public function createChild():void
{
    childFunction = new ChildFunction( var1, var2 );
    addChild( childFunction );
}

Child:

public var varA:uint;
public var varB:uint;

public function ChildFunction( varA:uint, varB:uint )
{
    trace( varA, varB );

    if ( stage )
    {
        onAddtoStage();
    }
    else
    {
        addEventListener( Event.ADDED_TO_STAGE, onAddtoStage );
    }
}

public function onAddtoStage( e:Event = null ):void
{
    trace( varA, varB );
}

In this example, I would get the proper values of var1 and var2 in the first trace, but then 0 and 0 in the second. Repeated testing indicates that after leaving the constructor function, the values of varA and varB are completely forgotten as soon as the constructor function is left, even though they're declared as public variables.

I admit there's a lot I don't know about Action Script, but this has me scratching my head. Any help is much appreciated. I know I could just look at the variables in the parent from the child, but that doesn't work for what I need; I need to hand the values down and store them.


Solution

  • It's a problem of scope.

    When you trace( varA, varB ); in ChildFunction, it is using the varA and varB that are passed in as arguments.

    When you trace( varA, varB ); in onAddToStage, it's using the public var varA:uint; and public var varB:uint; which have never been changed and should therefore be their default of 0.

    What I'm assuming you intended to do was to set the ChildFunction's public data in its constructor:

    public function ChildFunction( varA:uint, varB:uint )
    {
        trace( varA, varB );
        this.varA = varA;
        this.varB = varB;
    
        if ( stage )
        {
            ...