Strict Mode and Casting in Flash Actionscript 3
Today I came across a programming error when I tried to find the z-index of the movieclip (my_mc) when it is being clicked. Below was my code:
trace (getChildIndex(e.target)); // throw a compiled time error
When I tested the movie, Flash returned a complied time error- 1118:Implicit coercion of a value with static type Object to a possibly unrelated type flash.display:DisplayObject.
I was scratching my head and couldn’t quite figure out what when wrong. It took me a while to realise that Flash was giving me the error because the complier didn’t know that e.target in this case was indeed a movieclip. When I turned off the Strict Mode error warning at the Actionscript 3 Settings at the Publishing Settings page, Flash compiled the movie successfully and everything ran fine.
Naturally I was not satisfied having to ignore the error in order to run the movie. So I did a little more research and found that I could explicity type cast an object if the compiler didn’t know what the object type was. There were bascially two ways to solve the above problem. Instead of:
Replace that with:
trace (getChildIndex(e.target as MovieClip));
So now I have the proper code that meets the strict typing requirement and can be compiled successfully. 🙂