AS2 OOP: Class Structure
         by senocular  

Static
Static properties and methods in ActionScript 2.0, those that are consistent throughout all instances of a class, are now created with the new static keyword. In ActionScript 1.0 they were simply added directly onto the constructor function object. In a class file for ActionScript 2.0 static kind of serves as your doorway to the class object's constructor object.

static var variableName;
static function functionName(){ ...

Here's an example of a class using static.

// in French.as
class French {
static var fries:Number = 0;
 
static function recipe():Void {
trace("Just fry with a potato");
}
 
function fry (slice:Potato):Potato {
slice.prepare("cut");
slice.cook();
trace("Made a fry!");
fries++;
return slice;
}
 
//...
}
// in Flash movie
French.recipe(); // Just fry with a potato
 
trace(French.fries); // 0
var food1:French = new French();
food1.fry(new Potato()); // Made a fry!
trace(French.fries); // 1
var food2:French = new French();
food2.fry(new Potato()); // Made a fry!
trace(French.fries); // 2

Try it yourself! (zipped source)

Remember that static methods do not have access to non-static class properties, but non-static methods have access to them. Static methods don't because they are not associated with an instance. They are run directly off the class object itself. With this new class syntax, however, it may be tempting to do so this very thing since those properties seem so readily available. Try your best not to. If you can't, don't worry, the compiler will catch it and spit an error out at you complaining. The only thing that static methods do have access to are other static properties and methods. Class methods which are not static, however, have access to them all. They can access all properties and methods static or not, and therein lies the static advantages. Accessing static properties is just a little easier now with ActionScript 2.0.

One restriction ActionScript 2.0 adds to static properties and methods is that they cannot have the same names of other properties or methods in your class which are not static. This is possible with ActionScript 1.0, but because all class methods access static properties and methods directly by their name in ActionScript 2.0, they need to each be uniquely identified.

If you think about it, a class file has a lot of scopes in which it defines values for. Because of the access granted to each of these scopes, names of things within these scopes need to be unique.

[ a class code block references many scopes ]

Contained within the class brackets, much of this scope jumping is hidden. It's not really that important for that matter since most all that information is directly accessible to an instance and/or its methods. Sometimes you may want to restrict some of this access though - at least on some level.

 




SUPPORTERS:

kirupa.com's fast and reliable hosting provided by Media Temple.