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.

Actionscript:
  1. 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:

Actionscript:
  1. var displayObjCtr:DisplayObjectContainer = new DisplayObjectContainer();
  2. 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.

Actionscript:
  1. var clip:MovieClip= new MovieClip();
  2. 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.

Actionscript:
  1. 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:

Actionscript:
  1. (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!

Actionscript:
  1. 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!

33 Comments

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

[...] 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 [...]

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.

Josh Tynjala

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

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.

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

[...] 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″ [...]

Curtis J. Morley

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

Martin

Great post!
Saved my day.

Thanks.

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”

Andy

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

Andy

Thanks to Curtis too. his link got me here

Josh Tynjala

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.

Nmuta

I thought this.parent was written this._parent
Is the _parent syntax deprecated now? Please advise. Thanks.

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.

Josh

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

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.

Josh Tynjala

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

DallasNYC

Excellent article. Chrystal clear.

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…

Nicolas F.

Thanks you, it helped me a lot !

Amit

Cheers for that mate !! tht was really helpful !!

jimmi

omg.. i have lost so many days fighting with the 1119. You saved me bigtime.

Barry

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

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

[...] Why doesn’t the “parent” property work the same in ActionScript 3? Introduction to the Display List [...]

L’errore 1119 in ActionScript 3 | Marcello Surdi

[...] 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 [...]

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!

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);

SimpleAS3: An ActionScript Framework for Designers, Animators, and Part-time Coders - Josh Talks Flash

[...] 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 [...]

Jason

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

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!

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!

bioRex

Awesome!!
Thank you! I was about to kick my computer but you saved it haha

You were really helpful

Sakana

Thank you, very useful and well explain.

S.

Leave a Comment

Note: New comments may need to be approved before they appear.

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>

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