Demystify the “root” property of DisplayObject

— 2 minute read

Every DisplayObject has a property named “root”. What does this property refer to? Do all display objects share the same root object?

According to Adobe’s Help, the root property is the top-most display object in the portion of the display list's tree structure represented by that SWF file. In other words, root is the document class of that SWF. (By saying document class, I mean the movie clip that is linked with document class in Flash CS or the target class which you compile with Flex SDK)

There are other cases mentioned in the document:

  • Root of Stage is the Stage itself.
  • Root of a loaded image (jpg, png, gif) whose content is a Bitmap is the Bitmap.
  • If a DisplayObject is created by code and (for e.g. new Sprite()), its root is null until it is added to a container which has non-null root. (The container’s root will be passed to its child). The container is not necessary to be on stage.

Besides, I have made some experiments to come up with some more conclusions:

  • If we add a new display object directly to Stage (by pass document class), its root will be the Stage.
  • The root of document class is always itself even it is removed off stage (and then added again to stage) or even added to another display object which has a different root.

Below is my summary about root:

display list tree
display list tree
stage.root= stage
documentClass.root= documentClass
documentChild.root= documentClass
stageChild.root= stage
stageGrandChild.root= stage
loadedDocumentClass.root= loadedDocumentClass
loadedChild.root= loadedDocumentClass

Download my experiment code here.

Conclusion

The root object is just an old revived property from ActionScript 2. But back then, since new movie clips must be instanciated from another existing movie clip, all _root properties will point to a single top-most display object, and hence _root reference is consistent.

In ActionScript 3, because of this inconsistence in object reference, I think we should AVOID using root and should use other approaches to get your intended reference.

[Vietnamese tags: Giải mã đối tượng root của DisplayObject, AS3]