Packages are actually namespaces in ActionScript 3

Have you ever looked at the returned value of the function flash.utils.getQualifiedClassName() and wondered why it includes :: between the package and the class name? For example, if you pass in a MouseEvent instance, you’ll get the string value "flash.events::MouseEvent". The first time I tried it, I expected to receive "flash.events.MouseEvent" with a . because that’s how you reference a packaged class in an import statement. I always thought the difference was a little strange, but I just shrugged and went about my business. Today, though, my mind must have been feeling a little extra clever than ususal because it suddenly dawned on me: you use :: as an operator in ActionScript 3 to access a namespace.

With one simple test, it became unquestionably clear that packages in ActionScript 3 are really an abstraction built on top of namespaces. Try running the following code using the Flex SDK or the Flash authoring tool:

namespace flash_events = "flash.events";
trace( flash_events::MouseEvent ); //output: [class MouseEvent]

No import needed!

I imagine this has ECMAScript 4 roots. In general, many of the OOP features of AS3, like class and package syntax, are considered syntactic sugar. How can AS3 developers benefit from this knowledge? I have no idea, but it’s one of those discoveries that whispers, “someday, you may need me”.

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: Get the class used to create an object instance in AS3 « Josh Talks Flash

  2. sydd

    You can benefit from this, if you use Flex: Flex uses an namespace called mx_internal to hide stuff from the user. If you use the mx_internal namespace, you can access these hidden properties of Flex components. For example i love to use mx_internal::$addChild method – its for adding a non-Flex child to a Flex component. Since you add it directly, Flex wont do anything to this component.

    Basically Adobe uses this namespace thing to hide functions in a class without making them private.

  3. Josh Tynjala

    I think you misunderstood the point of this post, sydd. It wasn’t to introduce namespaces in their typical usage (like how Flex classes use mx_internal). Instead, it shows how a very core part of ActionScript 3, namely packages, is actually using namespaces behind the scenes. Many developers don’t realize that.

    One more thing, sydd. Rather than calling $addChild(), you should use rawChildren.addChild(). It’s a fully supported public API that is designed for the same thing that you’re trying to do.