ActionScript Classes

 <  Day Day Up  >  

Class-based development in ActionScript enables development of maintainable and scaleable solutions while grouping code logically. ActionScript 2.0 has an entirely new approach to class-based development that encourages developers to use best practices.

In previous versions of Flash, it was considered good practice to define all classes in separate ActionScript files. Doing this facilitated the use of version control systems and made working in a team environment on a large Flash project that much easier and more organized. In ActionScript 2.0, all class definitions must be located in separate ActionScript files. In addition, it is not possible to define classes on a timeline (such as in Frame 1 of an Actions layer). All native classes in ActionScript (for example, the MovieClip class) are stored in separate ActionScript files.

Referencing ActionScript Files

Each external ActionScript file can define only one class, and the file must share the same name as the underlying class. For example, a class called Product must be located in a file called Product.as. If you are not using the Professional version of Flash, you will need a separate editor for your ActionScript files. Editors include Dreamweaver, SciteFlash, and Notepad.

To use a custom user -defined class, the ActionScript file can be located in the same folder as the SWF file referencing that class. It is possible to use folders and subfolders to store class definitions by using the import keyword or by referring to the class in the script.

The following code illustrates two ways to refer to the Product class located in a subfolder called Data . This subfolder is also known as a package and Flash automatically builds that object for us in relation to the directory structure. Note that in contrast to Flash MX, the developer cannot use #includes to reference classes.

 var myProduct:Product = new Data.Product(); 

and

 import Data.Product; 

The class Keyword

The class keyword is a developer-friendly and intuitive way of doing the prototype chaining that you had to do in ActionScript 1.0; behind the scenes, the class keyword is building those prototype chains and registering your classes using Object.registerClass() , which makes it easier to use the class in component authoring.

A constructor function can be created in ActionScript 2.0 by defining a function with the same name as the class. However, if no constructor is defined, the class keyword automatically builds a constructor function. The class construct enables you to structure your code much more efficiently and in a way that is similar to other object-oriented languages, such as Java. It also provides you with the many debugging tools unavailable in Flash MX.

Examine a very simple class file located in the file Product.as:

 class Product {       var id:Number;       var prodName:String;       var description:String;       function Product (id:Number, prodName:String, description:String)       {             this.id = id;             this.prodName = prodName;             this.description = description;       } } 

The constructor function Product has the same name and case as the underlying class. If we do not specify a constructor, the class construct automatically creates that for us, but specifying a constructor can give us a lot more flexibility. In addition, note that the keyword this is no longer required when referring to properties; however, it still can be used in class definitions.

N OTE

The ActionScript 2.0 compiler generates accompanying files for every class that is created with the extension ".aso". These files contain the binary code that represents the class, and other scripts use these files for type checking. These files cannot be opened by Flash.


Public and Private Attributes

The use of the keyword public means that a method or property can be accessed outside a class; if public or private is not specified, ActionScript 2.0 assumes public. The keyword private indicates that the method or property can be referenced inside the class only.

N OTE

The private keyword in Flash MX 2004 works like the protected keyword in other languages because all methods and variables designated as private are accessible from any subclass of the class in which they were defined; this is not the case in other object-oriented languages.


Methods and properties can be designated as public and private; it is a best practice to always indicate whether a method or property is public or private.

Let's examine the Dump class, which you build later in this book. It serves to display complex data structures to assist in debugging. Note that only the dumpThis() method can be called outside the class; the dumpArray() and dumpObject() methods are called internally within the class by the public function dumpThis() .

 class Dump {       function Dump() {}      //constructor       public function dumpThis (theObject:Object):Void {             if (theObject instanceof Array) {                   dumpArray(theObject);             }else if (theObject instanceof Object) {                   dumpObject(theObject);             }else {                     trace (theObject);             }       }       private function dumpObject (theObject:Object):Void {             trace ("Object:");             for (var prop in theObject) {                          if (theObject[prop] instanceof Object) {                                dumpThis(theObject[prop])                    }else{                    trace (prop+":");                    trace (theObject[prop]);             }     }  } private function dumpArray (theArray:Object) :Void {               trace ("Array:");               var len = theArray.length;               for (var i=0;i<len;i++) {                     trace ("[" + i + "]");                    dumpThis(theArray[i]);       }    } } 

Static Attribute

Methods or properties designated in a class as static cannot be associated with an instance. The name of the class must be referenced directly, as in the following example:

 classclass Product {       static function getType():String {return "Product"}; } Product.getType(); 

Only static properties can be accessed inside static methods; it is not possible to access class instance variables. The static attribute can be used only within a class definition. An example of a class in ActionScript that uses only static methods and constants is the Math class.

The extends Keyword

For classes to inherit from other classes, the extends keyword can be used. In the following example, the class Drag inherits all public and private methods and properties from the MovieClip class; in this case, the code is using onPress() , onRelease() , startDrag() , and stopDrag() , all from the MovieClip class. In ActionScript 2.0, a class cannot inherit from multiple classes.

 classclass Drag extends MovieClip {           function Drag () {              onPress = doDrag();              onRelease = doDrop();        }        private function doDrag(){              this.startDrag();        }        private function doDrop(){                     this.stopDrag();        } } 

Dynamic Attribute

Any class that is designated as dynamic might add or remove dynamic properties at runtime. For example, if you call a method that does not exist on a regular class, you get the "No method with the name " error message. By defining that class as dynamic, you can call an undeclared method on the class in the instance, even if it is not in the class definition.

 dynamic class Drag extends MovieClip {       function Drag (){             onPress = doDrag();             onRelease = doDrop();       }       private function doDrag(){             this.startDrag();       }       private function doDrop(){              this.stopDrag();       } } 

By using the dynamic keyword in the preceding ActionScript code, you can easily add methods to an instance of the class by using createEmptyMovieClip() or createTextField() , which are methods of the MovieClip class.

Visual Class Linkage

It is now possible to link a visual object with a class file without using object.registerClass() . For example, Figure 1.4 shows a movie clip, mcBall , being linked to the Drag class. This enables a class that implemented drag-and-drop functionality to be linked to any visual object or to an underlying class. The Export for ActionScript check box must be checked to enable this feature. Of course, if you create visual objects in code, you can still use the object.registerClass() technique.

Figure 1.4. mcBall being linked to the Drag class.

graphics/01fig04.gif

Implicit Getters/Setters

In general, good object-oriented programming (OOP) practice dictates that functions methods are used to access and set properties. In Flash, you often had to access properties directly, as in the following examples:

 my_mc._x = 100; var xpos = my_mc._x; 

This is considered bad OOP practice and it is almost always better practice to build getter and/or setter functions to set properties. Consider the Product class you were working with earlier:

 class Product {       var id:Number;       var prodName:String;       var description:String;       function Product (id:Number, prodName:String, description:String)       {             this.id = id;             this.prodName = prodName;             this.description = description;       } } 

It certainly would be possible to set the prodName property in the following manner:

 var myProduct:Product = new Product(); myProduct.prodName = "Call Center Server"; 

However, this would be bad OOP practice and result in less maintainable applications. The established OOP way of doing this is to write getter and setter methods instead of accessing the properties directly. If the following class is used, there is no reason to ever have to access properties directly:

 class Product {       private var id:Number;       private var prodName:String;       private var description:String;       function Product (id:Number, prodName:String, description:String){             setID(id);             setProdName (prodName);             setDescription(description);       }       public function getId() :Number{             return this.id; }       public function setID (id:Number) :Void{             this.id = id; }       public function getProdName () :String{             return this.prodName; }       public function setProdName (prodName:String) :Void{             this.prodName = prodName; }       public function getDescription () :String{             return this.description;       public function setDescription (description:String) :Void{       this.description = description; } } 

After this class has been defined in an ActionScrpt file, the following code (for example, on a frame script) can be used to get and set properties. This is done instead of accessing the properties directly:

 var myProduct:Product = new Product(); myProduct.setID (1); myProduct.setProdName ("Call Center Server"); myProduct.setDescription ("Allows any call center service center to improve service"); 

Writing getter and setter methods manually can result in lots of extra code (and typing!), so Flash MX 2004 includes implicit getter and setter methods (these are syntactic shortcuts for the old Flash MX object, addProperty ). All implicit getter and setter methods must be public, and they use the keywords get and set within a class definition block.

Getter and setter methods are actually two separate methods; one gets the value of the property and one sets the value. Note that the getter and setter methods generally have the same name.

When getter or setter methods are called, you do not include parenthesis at the end as you do with other methods; in fact, your code almost looks like you are referencing properties, but they are in fact methods. Note that getter and setter methods cannot have the same name as existing properties within a class.

Getter and setter methods should be called within the class constructor, if properties are set there. Implicit getter and setter methods can seem confusing at first because they look just like the old getter and setter properties in Flash MX. Examine the following best practices Product class:

 class Product {       private var id:Number;       private var prodName:String;       private var description:String;       function Product (id:Number, prodName:String, description:String) //constructor       {             idNo = id;             productName = prodName;             productDescription = description;       }       public function get idNo() :Number {             return this.id; }       public function set idNo (id:Number) :Void {             this.id = id; }       public function get productName () :String {             return this.prodName; }       public function set productName (prodName:String) :Void {             this.prodName = prodName; }       public function get productDescription () :String {             return this.description; }       public function set productDescription (description:String) :Void {       this.description = description; } } 

Note that in the constructor, the setter methods are called to set the properties that are passed in. After getter and setter methods have been defined properly, you never need to set properties directly. The following code sets and gets the product id, product name, and product description, as shown in Figure 1.5:

 var myProduct:Product = new Product(); myProduct.idNo = 1; myProduct.productName = ""Call Center Server"; myProduct.productDescription = "Allows any call center to improve service"; trace (myProduct.idNo); trace (myProduct.productName); trace (myProduct.productDescription); 
Figure 1.5. ActionScript is now "smart" enough to figure out whether you are setting or getting a property.

graphics/01fig05.gif

 <  Day Day Up  >  


Object-Oriented Programming with ActionScript 2.0
Object-Oriented Programming with ActionScript 2.0
ISBN: 0735713804
EAN: 2147483647
Year: 2004
Pages: 162

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net