If you remember in as2 we had _root which let us access to methods and variables in the root of the project and refer to absolute paths, I thought that as3 didnâ€™t have _root propriety, but I was wrong. root property can be useful if you want to s
hare some value to all the classes in the project, add events to main class that call methods declared inside the class where we are working on or call generic methods declare in root class.
To use root propriety the class that you are working on most extend a DisplayObject (Sprite,MovieCLip,etcâ€¦) because you have to add the class to the parent class. And note, you canâ€™t use the root propriety in the constructor method, because the addChild havenâ€™t been process yet! Well letâ€™s stop writing and see some code:
In the Main class Iâ€™m declaring a variable named myValue which I did the proper sets and get. I am declaring two classes, in one of them I will set the value at the Main class and in the other I will get that value back. Iâ€™m also creating a movieClip just for test purposes.
In ExampleClass Iâ€™m setting myValue that is propriety of the Main class with some text and Iâ€™m tracing the movieClip that I create in the Main Class.
In AnotherClass Iâ€™m tracing the myValue propriety. So the result should be:
This value is inside the Main Class
So it works ok, you only have to be carefull not refer root inside the constructor method, have the certain that you already addChild the class when you are referring to root and that the class extends a display object. If you do that, you can too have access to stage propriety, letâ€™s check the next example:
The result should be or stage width.
Another way to access to main proprieties, methods, etcâ€¦ is with static members. In the next example Iâ€™m declaring a static property in the main class and setting and trace the value of it in the example class.
The result should be â€œHello Word!â€, if you didnâ€™t know this, read some books about object oriented programming and static members.
Another way to do the same thing is to pass the instance of main class as an argument to the other classes.
There are still another ways to access to the Main class code. I donâ€™t know which techniques are more correct, I usually use them all depending in what I need. I hope I help someone.