Why doesn’t the “parent” property work the same in ActionScript 3?

by Josh Tynjala

No, I’m not asking that question. Instead, I am going to answer it and explain the reasons why it’s not as easy to traverse the display list like you could in ActionScript 2. In addition, I’ll give you a couple options for how to get around any errors you may encounter when you need to “hack” up and down the hierarchy. Under most circumstances, I don’t recommend them, but I believe that there’s nothing wrong with knowing what you’re not supposed to do.

Let me begin with a recommendation. If you’re just starting with AS3, and you’re a little frustrated with the extra work these language changes make you do, please consider taking a short time to learn a little object-oriented programming principles and how to do things properly. Why? Well, some important benefits come from coding through best practices. First, it’s easier to catch bugs because the compiler is much smarter than it used to be. Silly mistakes that might go unnoticed in AS2 will be caught immediately in AS3. Second, your code will run many times faster because the compiler makes special optimizations with well-written code. No one can argue that fast and bug-free code is silly. The new language is trying to help you to achieve those results, so don’t fight it.

Now, let’s put my preaching about best practices behind us. One of the first things a lot of developers familiar with AS2 may discover is that code similar to the following doesn’t work anymore.

this.parent.parent.some.deeply.nested.movie.clip.x = 50;

If you try to compile code like that in AS3, the compiler will throw an error:

1119: Access of possibly undefined property some through a reference with static type flash.display:DisplayObjectContainer.

The new compiler is a little bit stricter than it used to be in the AS2 days of Flash 8 and below. Today, the compiler knows that a MovieClip’s parent property is of type DisplayObjectContainer. It might actually be a subclass, like Sprite or MovieClip, but the compiler can only guarantee that it’s a DisplayObjectContainer. This class is not dynamic. To add new properties, like a child MovieClip that can be accessed publicly, you need to subclass it. In other words, if you instantiate a DisplayObjectContainer directly, you can’t do something like this:

var displayObjCtr:DisplayObjectContainer = new DisplayObjectContainer();
displayObjCtr.myDynamicProperty = 12; //error

On the other hand, the MovieClip type that we all know and love is dynamic. You can add properties and methods and anything you want to it without restriction.

var clip:MovieClip= new MovieClip();
clip.mySpecialVariable = "hello!"; //okay!

“…but,” you say to yourself, “I know the parent of my symbol is a MovieClip!” Good for you. The compiler doesn’t know that for sure. It’s possible to remove any DisplayObject from its parent and add it to another. How’s the compiler (which isn’t running all the code. It’s just making it into a SWF) to know that the parent hasn’t changed to a Sprite, CheckBox, or something else when you run your code?

Since you know the answer, that a certain parent is always going to be a MovieClip, then you can explicitly tell the compiler, “It’s okay. Please assume this is a MovieClip rather than a DisplayObjectContainer. Trust me.” This is called casting.

MovieClip(this.parent.parent).some.deeply.nested.movie.clip.x = 50;

Personally, I prefer the “as” keyword for most casting, but you may use either. Take the time to learn more about each because they behave differently in subtle ways. Here’s an example of casting using the “as” keyword:

(this.parent.parent as MovieClip).some.deeply.nested.movie.clip.x = 50;

Notice that you don’t need to cast the other MovieClips. That’s because the compiler assumes dynamic properties are of type Object, which is another dynamic class. Everything is an Object in AS3, so this is fine for our purposes. If you’re looking to optimize your code, you should consider casting them too. AS3 runs a little bit slower when it only knows something is an Object.

Let’s Get Crazy. Turn Off Strict Mode!

Now, some folks think the extra work of casting is a pain. If you must traverse the display list, I recommend using casting as much as possible to keep the compiler aware about variable types. Let’s consider, though, the possibility of coding like we could in AS2, with no casting needed and all the flexibility of the good old days. Sounds interesting, you say? Read on.

When you create a FLA file for ActionScript 3.0 in Flash CS3, you get all the strict typing checking by default, as we’ve all seen. However, at it’s core, AS3 is still a dynamic language, and you can tell the compiler to shut up if you want. Here’s how you do it:

Screenshot of the strict mode checkbox
  1. Create a new ActionScript 3 FLA file.

  2. Then go into the Publish Settings, either from the File menu or the Properties panel.

  3. Under the Flash tab, click the Settings… button next to ActionScript version.

  4. Uncheck the Strict mode checkbox

Remember that AS2-like code that gave us an error before? If you try to use it with strict mode turned off, the compiler won’t complain at all!

this.parent.parent.some.deeply.nested.movie.clip.x = 50;

It’s very simple to set up a FLA file to work with strict mode off, as you can see, and I’m surprised that I haven’t seen it mentioned before. I created a sample Flash CS3 FLA file with strict mode disabled if you’d like a hands-on look at how I set it up. You’ll discover that it compiles and runs without error, but if you go back into the Publish Settings to re-enable strict mode, you’ll get compiler errors. Have fun, and don’t come complaining to me when someone yells at you for turning strict mode off. I warned you to leave it on!

About the Author

Josh Tynjala is an indie game developer, entrepreneur, Flash and Flex mercenary, and bowler hat enthusiast.

Discussion
  1. [...] so clever!  Josh over at ZeusLabs posted an article on the “parent” property and its use (or lack thereof) in AS3.  The article teaches you how to use parent in AS3 properly [...]

    posted by reintroducing.com Blogging Receptacle » Blog Archive » AS3 Has No “_parents” on 07.12.2007
  2. It’s good to point out that there is a difference with the two casting methods. When you cast with “as” and it fails, you’ll get a null value which then may trigger an exception down the line, whereas if you cast the other way you’ll get a runtime exception on that line so you know exactly where the problem lies.

    posted by Tim on 07.15.2007
  3. Tim, though I didn’t fully explain the differences, I added a sentence to note that the two methods have slightly different behavior.

    posted by Josh Tynjala on 07.15.2007
  4. I don’t think the differenced is subtle though. The method you prefer can be harder to debug since you’d have to go back down the stack trace to find out where the null value was created. Off topic from from the post… just wanted to share my thoughts since the topic came up at work the other day.

    posted by Tim on 07.18.2007
  5. [...] One of the best explanations of casting is written up by Josh Tynjala  go visit his  blog called “Why doesn’t the ‘parent’ property work the same in ActionScript 3″ [...]

    posted by curtismorley.com » Blog Archive » Flash CS3 / Flex 2 AS3 Error #1119 on 08.15.2007
  6. Josh,

    Great explanation. I have a post that deals specifically with ActionScript Error #1119 on my site at http://curtismorley.com/2007/06/13/flash-cs3-flex-2-as3-error-1119/ and I am pointing everyone here to learn about how parent works in AS3. Great Post. The way parent works in the displayObject is very well explained.

    Thanks,
    Curtis J. Morley

    posted by Curtis J. Morley on 08.15.2007
  7. Great post!
    Saved my day.

    Thanks.

    posted by Martin on 08.21.2007
  8. Nice article. I’m all in favor of turning Strict Mode off for more reasons than just this. This whole “possibly undefined” compiler error has gotten on my last nerve. No thanks, Adobe. Instead of defaulting to Strict Mode I’d like a default for “Loose Mode” or “Lets All Just Get Along Mode”

    posted by Justin on 08.26.2007
  9. thank you! thank you so much! make sure everybody knows! this has been giving me nightmares for weeks! – but its all good now!

    posted by Andy on 09.11.2007
  10. Thanks to Curtis too. his link got me here

    posted by Andy on 09.11.2007
  11. I recently added a more comprehensive article named Developing with the Display List in ActionScript 3 on the Yahoo! Flash Developer Center. It has more details, and I finish with some tips for developing your applications so that you don’t need to use the workarounds I described above.

    posted by Josh Tynjala on 09.11.2007
  12. I thought this.parent was written this._parent
    Is the _parent syntax deprecated now? Please advise. Thanks.

    posted by Nmuta on 09.13.2007
  13. Nmuta, the _parent property of a MovieClip that you know in AS2 is now just parent, without an underscore, in AS3. It’s not deprecated (you can still access a MovieClip’s parent), but simply renamed.

    posted by Josh Tynjala on 09.13.2007
  14. Great, I didnt understand anything with the “parent” stuff on as3. Now it is crystal clear! Thanx

    posted by Josh on 10.03.2007
  15. I think using the ‘as’ operator should really only be used to cast an expression to either the date or array classes, otherwise stick with the other method in case of exception errors? Still learning AS3 so I could be wrong with this.

    posted by Tim on 10.12.2007
  16. Nope, I’ve found many uses for the as operator where I can check for null afterwards and branch based on that.

    posted by Josh Tynjala on 10.12.2007
  17. Excellent article. Chrystal clear.

    posted by DallasNYC on 10.24.2007
  18. Thanks for the great article.

    I tend to code in strict mode for clients and in ‘CRAZY’ mode when I am working on more creative work. In any case, I’m glad Adobe gave us the option to work in either mode…

    posted by blprnt on 11.18.2007
  19. Thanks you, it helped me a lot !

    posted by Nicolas F. on 04.14.2008
  20. Cheers for that mate !! tht was really helpful !!

    posted by Amit on 04.23.2008
  21. posted by MMUG-Dublin Bloggers » Blog Archive » Display List and Containers and Casting on 05.01.2008
  22. omg.. i have lost so many days fighting with the 1119. You saved me bigtime.

    posted by jimmi on 05.07.2008
  23. you absolutely rock!! I’ve been finding a clear-cut, straightforward example of navigating paths in AS3 and you did it beautifully. Thanks!

    posted by Barry on 05.29.2008
  24. [...] Why doesn’t the “parent” property work the same in ActionScript 3? Introduction to the Display List [...]

    posted by SILK ROUTE » Blog Archive » [三腳貓的]AS3筆記-之AS3一玄:Error 1119 on 06.13.2008
  25. [...] Adobe ci debba costringere a fare il casting in queste situazioni. Ho letto di recente un’interessante articolo che fornisce questa spiegazione: “Ma, ” – ripeti a te stesso - ”Io so che il [...]

    posted by L’errore 1119 in ActionScript 3 | Marcello Surdi on 07.17.2008
  26. Is there some good reference to some strict practices like you have shown here? I was going nuts until I found out I had the strict setting on. I only found this thread after I figured it out, but I feel bad for all those people out there going crazy figuring out what is wrong with the code. Semperfi!

    posted by M.A.D. on 08.07.2008
  27. I was referring to this code:

    function showChildren(dispObj:DisplayObject):void {
    	for (var i:uint = 0; i < dispObj.numChildren; i++) {
    		var obj:DisplayObject = dispObj.getChildAt(i)
    		if (obj is DisplayObjectContainer) {
    			trace(obj.name, obj);
    			showChildren(obj);
    		} else {
    			trace(obj);
    		}
    	}
    }
    
    showChildren(stage);
    posted by M.A.D. on 08.07.2008
  28. [...] AS3 compiler is very strict compared to AS2. For instance, since the parent property on display objects is typed as DisplayObjectContainer, developers must often cast it as a different [...]

    posted by SimpleAS3: An ActionScript Framework for Designers, Animators, and Part-time Coders - Josh Talks Flash on 08.13.2008
  29. Thanks for the tip. Still, I don’t understand why Adobe needed to overhaul everything so dramatically.

    posted by Jason on 09.09.2008
  30. Hey! I’ve been coding AS3 for a little while now and I got used to it pretty good! But it was still useful reading your explaination! So I really appreciate you breaking down AS3 so simple!

    Thanks man – great work!

    posted by four times daily on 09.16.2008
  31. Good to see actionscript gaining casting. It’s been a while since I’ve used flash and I’m liking all the new features a lot!

    posted by Nic on 09.30.2008
  32. Awesome!!
    Thank you! I was about to kick my computer but you saved it haha

    You were really helpful

    posted by bioRex on 10.19.2008
  33. Thank you, very useful and well explain.

    S.

    posted by Sakana on 10.30.2008
  34. Thank you! This post solved a ton of problems!

    posted by Tom on 01.22.2009
  35. thanks for the explanation! that helps a lot :p

    posted by Erwan on 03.18.2009
  36. Oh wow. It’s already been said but I’ll say it again’ You. Are. The. Champion. Thank you sooooo much.

    posted by Shaedo on 04.03.2009
  37. Thank you!
    Genius!

    posted by AS3 Rookie on 04.07.2009
  38. try this-like,
    this.parent.parent["some"].deeply.nested.movie.clip.x = 50;

    posted by 不惑仔 on 04.11.2009
  39. THANK YOU! I wasted hours trying to solve this simple problem and your expanation was the first and only I found that made it clear. THANKS!

    posted by Andy on 04.23.2009
  40. thanks man, very good job.

    posted by Ernest on 05.05.2009
  41. hero.

    thanks.

    posted by Joshua on 05.25.2009
  42. I’m glad I read all the way to the end. I didn’t know that you could switch strict mode off!!

    It’s tempting to code in ‘crazy mode’, but to become a better programmer, I’ll stick to strict. Sometimes I want to ask why AS3 makes everything so hard, but I guess we gain with better performance.

    posted by flashbynight.games on 05.27.2009
  43. omg thank you. I don’t know how many hours of frustration you saved me, and i don’t want to :)

    posted by magii on 06.09.2009
  44. Oh… my… GOD!!! Thankyou so much!! Seriously, I don’t know where you learn stuff like this

    posted by Daniel Smith on 07.15.2009
  45. I’ve been coding in AS2 for ages and I’m finding the transition to AS3 quite frustrating. One of the frustrations regards traversing the display list. Communicating with movie clips in AS2 was simple and logical. Doing the same thing is AS3 is very painful.

    I find that this solution works well when you’re traveling from the stage into movie clips for eg:

    this.mc1.mc2.gotoAndPlay(5);

    However if you try to communicate between movie clips via the stage, Flash still throws up errors whether you are in strict mode or not.

    For example you have this code in mc1

    parent.mc2.gotoAndPlay(5);

    where you want Flash to do something once the play head has reached in mc1 by going back to the stage and then into mc2.

    I find it is relatively easy to traverse the display list from the stage into movie clips but traveling backwards is a nightmare…or am I missing a fundamental point?

    posted by AB on 07.21.2009
  46. AB, as I explained in the post, you should cast parent to something like MovieClip to access children.

    Another option is to use getChildByName(), but that will probably require some casting too.

    However, the best way for a display object to communicate with a sibling is to dispatch an event to which the parent can listen. The parent can do whatever is needed on its other child when it receives the event.

    posted by Josh Tynjala on 07.21.2009
  47. Thank you very much! Your article saved me a lot of time as well! Thanks again!

    posted by PoteN on 07.26.2009
  48. Josh, its been said many times before but THANK YOU! for this. Been scratching head last two days why cant access another child MovieClip in the same parent MovieClip from a button inside my 1st child MovieClip. Your A Star.

    Only question is why is it ‘(this.parent.parent) and not just (this.parent) to go up one level?

    cheers again Trev.

    posted by Trev on 10.10.2009
  49. Hi again, ignore my last question, just thought about it and understand why now, im trying to access the parent movieClip of the movieClip that is the parent of my button :)

    I’d recommend writing out a flowchart / tree-chart so you can see the relationships visually.

    Cheers

    posted by Trev on 10.10.2009
  50. Haha, its like a challenge.

    The option to turn the strict compiler off is there, but is it giving up? Feels like it to me.

    posted by Efehan on 11.06.2009
  51. Very Nice post!! You saved my day dear!! Thanks.

    posted by Vishwa on 11.16.2009
  52. Awesome page, have been looking for this solution forever :)

    posted by Marcus on 11.17.2009
  53. Very nice post, congratulation. I’m an italian graphic designer who starts with AS 3.0 some month ago and I found this article very interesting.

    posted by Andrea on 11.19.2009
  54. Very useful thanks.
    However I’m still having a few problems when writing my own classes, as I can’t refer to other classes within them.
    And unfortunately I can’t find an option to turn off strict mode while in .as files.
    For example here is (some of) the code in the class.. any suggestions on getting around the error ‘The definition of base class Graphics (or the highest parent class I list) not found.’

    public class DrawLine extends Graphics
    {
    	protected var x1Pos;
    	public function DrawLine(...)
    	{
    		Graphics.beginFill()
    	}
    }
    posted by Adam F on 11.20.2009
  55. Turning off Strict Mode applies to ActionSCript files as well. It’s not just the timeline.

    You still must import classes to extend them, even with Strict Mode off. If you want to extend Sprite, you still need this:

    import flash.display.Sprite;
    posted by Josh Tynjala on 11.20.2009
  56. thank you.

    posted by idoyan on 01.27.2010
  57. Thanks a lot!! you are wonderful man!! You are an excellent friend. Thanks for share your knowledge. God Bless You.

    posted by manuel guillen on 02.14.2010
Share Your Thoughts

To display code in comments: <pre>Code here. May be multiline. Format XML with &gt; and &lt; entities.</pre>

Some HTML allowed in comments: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>