Instance and class members 165
Instance and class members
In object-oriented programming, members (properties or methods) of a class can be either
instance members or class members. Instance members are created for, and copied into, each
instance of the class; in contrast, class members are created just once per class. (Class members are
also known as static members.)
To invoke an instance method or access an instance property, you reference an instance of the
class. For example, the following code invokes the
showInfo() method on an instance of the
MovieClip class called
clip_mc:
clip_mc.showInfo();
Class (static) members, however, are assigned to the class itself, not to any instance of the class. To
invoke a class method or access a class property, you reference the class name itself, rather than a
specific instance of the class:
ClassName.classMember;
For example, the ActionScript Math class consists only of static methods and properties. To call
any of its methods, you don’t create an instance of the Math class. Instead, you simply call the
methods on the Math class itself. The following code calls the
sqrt() method of the Math class:
var square_root:Number = Math.sqrt(4);
Instance members can read static members, but cannot write them. Instance members are not
enumerable in
for or for..in loops.
Creating class members
To specify that a property of a class is static, you use the
static modifier, as shown below.
static var variableName;
You can also declare methods of a class to be static.
static function functionName() {
// function body
}
Class (static) methods can access only class (static) properties, not instance properties. For
example, the following code will result in a compiler error, because the class method
getName()
references the instance variable
name.
class StaticTest {
var name="Ted";
static function getName() {
var local_name = name;
// Error! Instance variables cannot be accessed in static functions.
}
}
To solve this problem, you could either make the method an instance method or make the
variable a class variable.