Create a custom classAlthough 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. Do not enter the script in your lesson FLA file.
function Product (id:Number, prodName:String, price:Number)
{
this.id = id;
this.prodName = prodName;
this.price = price;
}
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. Note The following ActionScript is an example only. Do not enter the script in your lesson FLA file.
class Product
{
// variable declarations
var id:Number
var prodName:String
var price:Number
// constructor
function Product (id:Number, prodName:String,
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. Do 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. Write methods within the class that will access these variables directly. Different methods should 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. Specify the data type for method return valuesYou must indicate data types for values returned by methods after the method name and list of parameters, as in the following example: Note The following ActionScript is an example only. Do not enter the script in your lesson FLA file.
public function getProductName() :String
{
return name;
}
If no value is returned (for example, a property is being set), the data type is
Void :
public function setProductName(productName:String) :Void
{
this.productName=productName;
}
Build a custom classYou'll now build a new Product class with getter and setter methods and create an object from the Product class.
|