Recipe 2.4. Creating Static Methods and Properties


Problem

You want to create methods and properties that are directly accessible from the class rather than from instances of the class.

Solution

Use the static attribute when declaring the property or method.

Discussion

By default, properties and methods are instance properties and methods, which means they are defined for each instance of the class. If the Example class defines a _id property and a getId( ) method then, by default, each instance of Example has its own _id property and getId( ) method. However, there are cases in which you want the property or method to be associated with the class itself rather than with instances of the class. That means that no matter how many instances of the class there may be, there is just one property or method. Such properties and methods are called static properties and methods.

There are examples of static properties and methods in several of the intrinsic Flash Player classes. For example, the Math class defines a round( ) method. The round( ) method is static and is, therefore, accessible directly from the class:

trace(Math.round(1.2345));

The Math class consists entirely of static methods and constants. However, a class can have both static and instance methods and/or properties. For example, the String class consists primarily of instance properties and methods. However, the fromCharCode( ) method is declared as static. The fromCharCode( ) method returns a string based on the character codes passed to the method. Since the method isn't associated with any one String instance, it does not make sense to make the method an instance method. However, it does make sense to declare the method as a static method.

You can declare a property or method as static using the static attribute. The static attribute is always used in combination with the public, private, protected, or internal attribute.

For example, the following declares a private static property called _example:

static private var _example:String;

The order in which the attributes appear doesn't matter. For example, static private is the equivalent to private static.

One common and important use of static properties and methods is the Singleton design pattern, whereby a class has a single managed instance. Singleton classes have a private static property that stores the one instance of the class as well as a public static method that allows access to the one instance.

See Also

Recipe 2.1




ActionScript 3. 0 Cookbook
ActionScript 3.0 Cookbook: Solutions for Flash Platform and Flex Application Developers
ISBN: 0596526954
EAN: 2147483647
Year: 2007
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net