Now that you have learned to create a basic and functional class, Product, we are going to make a shopping cart to hold our Actionscript 2.0 class Product. Here is the class code that we will be creating:
import com.ahfx.Product;
class com.ahfx.Shopping {
private var cart:Array;
private var elementCount:Number;
function Shopping(){
cart = new Array(20);
elementCount = 0;
}
function addElement(object){
cart[elementCount++] = object;
}
function getTotal():Number{
var total = 0;
var i;
for(i=0;i<elementCount;i++){
var tempProduct:Product = cart[i];
total += tempProduct.getTotal();
}
return total;
}
function size():Number{
return elementCount;
}
function getElement(index){
return cart[index];
}
}
Please create an actionscript file (Shopping.AS) and copy the above code into the file. (If you don't know where to save your actionscript files please refer to our Actionscript 2.0 Basic page.
The first thing we need to do is import the Product class that we created earlier. import com.ahfx.Product. We will be using an Array to act as our Shopping cart. This array will hold our Products. The elementCount is going to be the number of Products in our Shopping cart.
Unlike our Product constructor, our Shopping constructor has some code in it. This code creates the array and sets the elementCount to 0.
The first method, addElement(), will insert a Product into our Shopping cart.
SUPPORT THIS SITE If this tutorial helped you, show your support and send me something from my wish list. Click on an item below and then choose Adam Hayes (Gift Registry Address) for the Ship to Address. It is that easy!