Variables and constants

Actionscript 3 guide to constants and variables.

This article assumes you have a knowlege of Classes and instances.

public class Cow extends Mammal {
	protected static const NUM_LEGS:uint = 4;
}

Let's dissect this cow, specifically, the NUM_LEGS constant.

There are 6 parts to this declaration:
protected
static
const
NUM_LEGS
:uint
4

I'm going to explain them backwards in order to go from simplest to most complicated.
4 - The value to assign to the variable or constant. If this is a constant, this is the only place you can assign a value.
:uint - The type declaration. For more information on data types: http://livedocs.adobe.com/flex/3/html/help.html?content=03_Language_and_Syntax_11.html.
const - This can either be const for a constant, or var for a variable. A const can only be assigned once and immediately, a var can be set at any time. If you are setting a variable, use camel case: myAwesomeVariable. If you are setting a constant, use all capitals: MY_AWESOME_VARIABLE.
static - This modifier either exists if the variable is static, or absent if it is not. A non-static variable (a regular variable) is a variable that is at the instance level. A static variable is a variable that applies to the class level.
Example:

public class SomeClass {
	public static var foo:String = "foo";
	public var bar:String = "bar";
 
	// Constructor
	public function SomeClass() {
		bar = "bar2";  // Could also be written as: this.bar = "bar2";
		foo = "foo2";  // Could also be written as: SomeClass.foo = "foo2";
	}
 
 
}
trace(SomeClass.foo); // foo
 
var myInstance:SomeClass = new SomeClass();
trace(myInstance.bar); // bar2
 
trace(SomeClass.foo); // foo2

protected - This is the variable's visibility. The four possible visibility modifiers are: private, protected, internal, public.

  • Private means that only the class that declared the variable has access to the variable. This is not instance level, if you create two instances of Cow, then cowA can access private variables on cowB.
  • Protected means that all sub-classes of the class that declared the variable has access to it.
  • Internal means that all classes in the same package as the declaring class has access to this variable.
  • Public means that everything has access to this variable.

There is one more possibility, and that is using namespaces to define the visibility of a variable. That is beyond the scope of this article, but be aware that you can use a namespace to give a custom visibility to an actionscript variable.