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

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 Josh Tynjala

Josh Tynjala is a frontend developer, open source contributor, bowler hat enthusiast, and karaoke addict. You might be familiar with his project, Feathers UI, an open source user interface library for Starling Framework that is included in the Adobe Gaming SDK.

Discussion

  1. Pingback: reintroducing.com Blogging Receptacle » Blog Archive » AS3 Has No “_parents”

  2. Tim

    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.

  3. Tim

    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.

  4. Pingback: curtismorley.com » Blog Archive » Flash CS3 / Flex 2 AS3 Error #1119

  5. Justin

    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”

  6. Andy

    thank you! thank you so much! make sure everybody knows! this has been giving me nightmares for weeks! – but its all good now!

  7. Josh Tynjala

    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.

  8. Josh

    Great, I didnt understand anything with the “parent” stuff on as3. Now it is crystal clear! Thanx

  9. Tim

    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.

  10. blprnt

    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…

  11. Pingback: MMUG-Dublin Bloggers » Blog Archive » Display List and Containers and Casting

  12. Barry

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

  13. Pingback: SILK ROUTE » Blog Archive » [三腳貓的]AS3筆記-之AS3一玄:Error 1119

  14. Pingback: L’errore 1119 in ActionScript 3 | Marcello Surdi

  15. M.A.D.

    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!

  16. M.A.D.

    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);
  17. Pingback: SimpleAS3: An ActionScript Framework for Designers, Animators, and Part-time Coders - Josh Talks Flash

  18. Jason

    Thanks for the tip. Still, I don’t understand why Adobe needed to overhaul everything so dramatically.

  19. four times daily

    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!

  20. Nic

    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!

  21. Shaedo

    Oh wow. It’s already been said but I’ll say it again’ You. Are. The. Champion. Thank you sooooo much.

  22. Andy

    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!

  23. flashbynight.games

    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.

  24. Daniel Smith

    Oh… my… GOD!!! Thankyou so much!! Seriously, I don’t know where you learn stuff like this

  25. AB

    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?

  26. Josh Tynjala

    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.

  27. Trev

    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.

  28. Trev

    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

  29. Andrea

    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.

  30. Adam F

    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()
    	}
    }
  31. Josh Tynjala

    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;
  32. jose

    Guy you are awesome thx for helping me with this. for a moment i thought parent was unaccessible from asc3 and was a little bi limitedfor a year to he point i couldn’t create my age of empires likegame now i can thx a lot

  33. Oscar

    Thank you very much! I was looking how to do it correctly in AS3 and not just turning off the strict mode.

  34. Malika

    Thank you very much for posting this. I’m new to actionscript so even though the focus of your article was to explain why the parent method for as3 is better, I learned what it means to actually access a parent class.

  35. John Anderson

    You saved another one who has put off AS3 for ever because of stuff like this. It worked. I don’t understand what “casting” means but it got me past the road block. My example looked like:

    stop();
    trace(“we are at the end”);
    (this.parent as MovieClip).beach2_mc.visible = true;
    (this.parent as MovieClip).beach2_mc.play();

    I still don’t like AS3, it’s way over blown for making simple animations…

  36. Mariana

    THANK YOU!!!

    I wasted almost two weeks trying to pass data between parent & child swfs until I read your article.