Wed Oct 14 02:20:48 2009
Sometimes it can be a little difficult to get the specific "child" you want in ActionScript 3 by calling its name directly. Also, the use of getChildAt() and getChildByName("") doesn't work because they are outside the scope of the current class in question. Well, this is where you could try casting.
For example, say that I have three classes. One called Main.as, one called Second.as and one called Third.as, each containing a single MovieClip containing a Square, Circle and Triangle respectively. Main imports Second and and Third and so becomes their "parent". The result is a Square, Circle and Triangle on the stage.
Now say that I want to access Third from Second to change the scale or some other property of Third's triangle. Well, I would need to use the this.parent.getChildAt(position).getChildAt(position) or maybe this.parent.getChildByName("second).getChildByName("triangle"), that is, if I had given them names. However, this is where you would run into problems. Flex/Flash just doesn't know what you are talking about.
Instead, by casting all instances and clips to "MovieClip" and holding them inside variables, you will ensure that Flex/Flash knows exactly what you want to access and what type of object it is.
Here's what I'm talking about
//this.parent.getChildAt(1).getChildAt(0) just doesn't work. It's outside the scope
//of the class called Third.
var sec:MovieClip = MovieClip(this.parent.getChildAt(1));
var tri:MovieClip = MovieClip(sec.getChildAt(0));
tri.scaleX = 2;
I know that some will complain that there is a better way to code and a good coder wouldn't code this way, and I would say I agree for the most part. However sometimes, whether it be a quick fix, or a quick add-on to an existing application coded by someone else, sometimes this will come in handy. After all, we can't guarantee the work of others.
If you would like a closer look, I have provided some fully annotated files here