
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Methods
|
93
Therefore, any attempt to access an instance property from a class method results in
the following compile-time error:
Instance variables cannot be accessed in static functions.
However, a class method can legally create an instance of a class and then access its
instance properties, as shown here:
class SomeClass {
private static var obj:SomeClass;
private var prop:Number = 10;
public static function doSomething ( ):Void {
// Create an instance of SomeClass and store it
// in the class property obj.
obj = new SomeClass( );
// Access an instance property, prop, of instance stored in obj.
trace(obj.prop); // Displays: 10
}
}
In the preceding code, SomeClass defines a class property, obj, and an instance prop-
erty,
prop. When the class method doSomething( ) is invoked, it creates an instance of
SomeClass, stores it in
obj, and accesses the instance property, prop. We’ll revisit this
theoretical structure when we study the Singleton pattern in Chapter 17.
Let’s be clear that class properties (declared using
static var) and instance proper-
ties (declared using
var) are both declared outside of class methods and instance
methods. Any variables declared within a method using the
var keyword are consid-
ered local variables. For example, you can’t declare a class property by simply ...