118 Chapter 15:Work with Objects and Classes Using ActionScript 2.0
Creating a custom class
While ActionScript includes many classes of objects,such as the MovieClip class and the Color
class,there will be times when you need to construct your own classes so you can create objects
based on a particular set of properties or methods.
To create a class that defines each of the new objects,you create a constructor for a custom object
class and then create new object instances based on that new class,as in the following example:
Note:The following ActionScript is an example only.You should not enter the script in your lesson
FLA file.
function Product (id:Number,prodName:Name,price:Number)
{
this.id:Number =id;
this.prodName:String =prodName;
this.price:Number =price;
}
In order to properly define a class in ActionScript 2.0,you must surround all classes by the class
keyword,and you must declare all variables in the constructor outside of the constructor.
Following is an example:
Note:The following ActionScript is an example only.You should not enter the script in your lesson
FLA file.
class Product
{
//variable declaration
var id:Number
var productName:String
var price:Number
//constructor
function Product (id:Number,prodName:Name,price:Number)
{
this.id =id;
this.prodName =prodName;
this.price =price;
}
}
To create objects from this class,you could now use the following code:
Note:The following ActionScript is an example only.You should not enter the script in your lesson
FLA file.
var cliplessPedal:Product=new Product(1,"Clipless Pedal",11);
var monkeyBar:Product=new Product(2,"Monkey Bar",10);
However,in ActionScript 2.0,variables that are part of a class structure should not be accessed
directly.You should write methods within the class that will access these variables directly.There
should be different methods that get and set properties (known as “getter ” and “setter ” methods).
You must indicate the data type for both a method ’s return value and any parameters that are
passed to the method when it is called.