Recipe 2.7. Creating Constants


Problem

You want to declare a constant.

Solution

Declare it just like you would declare a property, except use the const keyword in place of var.

Discussion

As the name constant implies, constant values do not change. Constants are useful when you have complex values that you want to be able to reference by a simple identifier or when you want to be able to use compile-time error checking for values. Math.PI is an example of a constant that contains a complex value (which is the value of pi, or 3.14159). MouseEvent.MOUSE_UP, which contains the value mouseUp, is an example of a constant that allows you to use error-checking. When you add an event listener for the mouse up event, you can use the string value mouseUp. However, if you accidentally have a typo, you won't be notified of an error, and your code won't work as expected:

// This is valid code, but because of the typo (mousUp instead of mouseUp) the  // code won't work as expected. addEventListener("mousUp", onMouseUp);

Using a constant helps. If you accidentally misspell the constant, you will receive a compile error that helps you track down the error:

// This causes a compile error. addEventListener(MouseEvent.MOUS_UP, onMouseUp);

The syntax for declaring a constant is very similar to that for declaring a standard property. However, rather than using the var keyword you use the const keyword. Although not required, the majority of constants also happen to be public and static. If you want a constant to be public and static, you must use the correct attributes. Additionally, you must assign a value for a constant when declaring it:

static public const EXAMPLE:String = "example";

By convention, constant names are all in uppercase. This convention makes it easy to identify and differentiate constants from properties.

See Also

Recipe 2.4




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