Constant and Static Variables in AS 3.0
Posted by dougr | Posted in ActionScript, OOP | Posted on 03-04-2009 | 5,358 views
Tags: ActionScript, linkedin, OOP
4
Today a question came up regarding the difference between constant fields and static fields and I thought it noteworthy to mention here as it is easy to casually use static when one’s intention is really to define a constant. Prior to AS 3.0, const was not available.
In short, a field declared as static const is indeed read-only, however, if declared as static it may be writable from inside or outside of its containing class, depending upon its access modifier (see Basic Modifiers below), and there is not a requirement for an instance of that class to be created in order for it to be referenced. Fields declared as constants may not be modified, they are constant.
It is interesting to note that a static field declared in a class may have the same name as an instance variable – the rule is that while both vars of the same name may be used in the instance, the static variable must be preceded by the classname (i.e. MyClass.variableName), whereas the instance variable would simply be declared by name.
Basic Modifiers:
Internal: the default if no modifier is specified – allows internal and package level access
Private: provides the greatest degree of access restriction – allows only internal access
Public: provides the least degree of access restriction – its an all-access pass
Protected: provides package level access restriction – allows internal and subclass access












I think that you meant, “In short, a constant declared with a static….”. A public static variable is modifiable from outside and within it’s class. Constants are always read-only.
Rich, Yep, that is correct when using a public modifier – thanks – will make edit to that effect as its important to point that out. Much appreciated!
Cool, but I think you might have misunderstood my comment. A static variable is a property of a class, as opposed to a property of the objects that class creates. Defining a property as static has no bearing on whether the property is read-only or not. Defining a property as a “var” inherently indicates that the value can change (it is variable), whereas defining a property as a “const” indicates that that particular value is pretty much set in stone for the life of the program (it’s constant). The various access modifiers only specify from where the value can be read from.
Oh snap – i did misunderstand – I see what i did – time for a re-write