12.3. Adding Properties to an Object Instance
Problem
You want to add custom properties (variables) to an object (an instance of a class).
Solution
Attach the new property to the object using an assignment statement and the dot operator.
Discussion
Objects derived from the built-in ActionScript classes have standard
properties. For example, arrays have length
properties, movie clips have _x
and
_y
properties, and Sound
objects have position
and
duration
properties. But aside from these standard
properties, you can add custom properties to any object in
ActionScript. You can add new properties to an object (or change an
existing property’s value) by simply assigning the
property a value. If the property does not yet exist, ActionScript
creates it automatically.
myMovieClip.myProperty = "some value";
Custom properties of movie clip
objects are sometimes referred to as
timeline variables, as discussed in Recipe 1.12. However, you can apply the same
principle not only to movie clip objects, but to any kind of object.
For example, the following code adds a custom property to an array
named myArray
:
myArray.myProperty = "some value";
Attaching properties to objects is invaluable. For example, custom properties can store a value that is used internally within an event handler method (or any other method) of the object. You can initialize the property value outside any of the methods and then access it within a method. This technique creates a variable whose value persists between function invocations ...
Get Actionscript Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.