User Guide
96 Chapter 3: Using Best Practices
• “Using the this keyword” on page 96
• “Using scope in classes” on page 97
Avoiding _root
There are several ways to target instances that let you avoid using
_root; these are discussed later
in this section. Avoid using
_root in ActionScript because it can cause SWF files that load into
other SWF files to not work correctly. The
_root identifier targets the base SWF file that is
loading, not the SWF file using relative addressing instead of
_root. This issue limits code
portability in SWF files that are loaded into another file, and, particularly, in components and
movie clips. You can help resolve problems using
_lockroot, but only use _lockroot when
necessary (such as when you are loading a SWF file but do not have access to the FLA file). For
more information on using
_lockroot, see “Using _lockroot” on page 96.
Use
this, this._parent, or _parent keywords rather than _root, depending on where your
ActionScript is located. The following example shows relative addressing:
myClip_mc.onRelease = function() {
trace(this._parent.myButton_btn._x);
};
All variables must be scoped, except for variables that are function parameters and local variables.
Scope variables relative to their current path whenever possible, using relative addressing, such as
the
this keyword. For more information on using the this keyword, see this in Flash
ActionScript Language Reference.
Using _lockroot
Flash MX 2004 introduced
_lockroot as a way to solve the scoping issues sometimes associated
with using
_root. Although this solves many problems with applications, consider _lockroot as
a workaround for problems caused by using
_root. If you experience problems loading content
into a SWF file or a component instance, try applying
_lockroot to a movie clip that loads the
content. For example, if you have a movie clip called
myClip_mc loading content, and it ceases
working after it is loaded, try using the following code (placed on the main Timeline):
this._lockroot = true;
For more information on using _lockroot, see MovieClip._lockroot in Flash ActionScript
Language Reference.
Using the this keyword
Whenever possible, use the
this keyword as a prefix instead of omitting the keyword, even if
your code works without it. You can use the
this keyword to learn when a method or property
belongs to a particular class. For example, for a function on the main Timeline, write
ActionScript using the following format:
circle_mc.onPress = function() {
this.startDrag();
};
circle_mc.onRelease = function() {