13.5.6.1. Using the array-element access operator
As we saw in Chapter 5, "Operators", and Chapter 12, "Objects and Classes", the
properties of an object may be retrieved via the dot operator or
through the array-element access operator, [ ].
For example, the following two statements are equivalent:
myObject.myProperty = 10;
myObject["myProperty"] = 10;
The array-element access operator has one important feature that the
dot operator does not; it lets us (indeed requires us to) refer to a
property using a string expression rather than
an identifier. For example, here's a
string concatenation expression that acts as a valid reference to the
property myProperty:
myObject["myProp" + "erty"];
We can apply the same technique to create our instance and movie
references dynamically. We already learned that clip instances are
stored as properties of their parent clips. Earlier, we used the dot
operator to refer to those instance properties. For example, from the
main timeline we can refer to clipB, which is
nested inside of another instance, clipA, as
follows:
clipA.clipB; // Refer to clipB inside clipA
clipA.clipB.stop( ); // Invoke a method on clipB
Because instances are properties, we can also legitimately refer to
them with the [ ] operator, as in:
clipA["clipB"]; // Refer to clipB inside clipA
clipA["clipB"].stop( ); // Invoke a method on clipB
Notice that when we use the [ ] operator to refer
to clipB, we provide the name of
clipB as a string, not an identifier. That string
reference may be any valid string-yielding expression. For example,
here's a reference to clipB that involves a
string concatenation:
var clipCount = "B";
clipA["clip" + clipCount]; // Refer to clipB inside clipA
clipA["clip" + clipCount].stop( ); // Invoke a method on clipB
We can create clip references dynamically to refer to a series of
sequentially named clips:
// Stop clip1, clip2, clip3, and clip4
for (var i = 1; i <= 4; i++) {
_root["clip" + i].stop( );
}
Now that's powerful!
13.5.6.4. The _name property
As we learned earlier in Section 13.3.3, "Instance Names", every instance's name is stored
as a string in the built-in property _name. We can
use that property, as we saw in Example 13-2, to
determine the name of the current clip or the name of some other clip
in an instance hierarchy:
_name; // The current instance's name
_ parent._name // The name of the clip that contains the current clip
The _name property comes in handy when we want to
perform conditional operations on clips according to their
identities. For example, here we duplicate the
seedClip clip when it loads:
onClipEvent (load) {
if (_name == "seedClip") {
this.duplicateMovieClip("clipCopy", 0);
}
}
By checking explicitly for the seedClip name, we
prevent infinite recursion -- without our conditional statement,
the load handler of each duplicated clip would
cause the clip to duplicate itself.