Thursday, 6 May 2010

Access Document Class in ActionScript 3.0

Consider a case where there are two classes called Main, and Other. The class Main is the Document Class, which has instantiated an object of the class Other. Here for the Class Other to access the methods of the class Main, can be easily done by creating an instance which is a static variable of the class Main which can be called only through the class. Static variables are associated with a class and not with instance of the class.
See example below:
//Main.as
package {

import flash.display.Sprite;

public class Main extends Sprite
{
public static var mainInstance:Main;
private var _child:Other;

public function Main()
{
mainInstance = this;
_child = new Other();
}

public function foo():void
{
trace("hello from document class");
}
}
}

//Other.as
package {

import flash.display.MovieClip;

public class Other {

public function Other()
{
Main.mainInstance.foo();
}
}
}

You can use getter if you don't want to expose the variables.
●๋•‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗●๋•