Writing an ActionScript 3 class

actionscript 3 class
Here are some basics of ActionScript 3 class, you should study before you start writing an AS3 class. It would be your great encounter with ActionScript 3 class. If you have understood very basic things explained in previous tutorial, you can upgrade your understanding here at a progressive speed. Follow the steps ahead and start writing your more advanced ActionScript 3 class right away.

1- ActionScript 3 class structure

This is the generic structure of ActionScript 3 class you may write in AS file. I am going to follow the same structure to explain you “writing an ActionScript 3 class” with an extended example. Create a new ActionScript File and save it as Profile.as within the said directory path structure …/ com/ slicepages/ tutorials/. Copy the code above and keep editing the file as you move ahead.

package {
//import statements

   public class Profile{

      public function Profile(){	//This is Constructor Method
      //Constructor statements here
      }

      //define Properties
      //define Methods
      //define Events - not included in this tutorial
   }
}

2- Package statement

When you are working with lots of ActionScript 3 class and .as files, the chances of namespace clashes are high between code from different files. A Package can be defined as a grouping of related‒type classes with similar functionalities, providing access protection and name space management. Since the package creates a new namespace, there won’t be any name conflicts with names in other packages. The package statement should be the first line in the source file.

As a convention, software companies use their reversed Internet domain name to begin their package names‒ for example, com.slicepages.tutorials for a package named tutorials created by a programmer at slicepages.com. The directories on the file system must match the package hierarchy. For example, the classes in the com.slicepages.tutorials will live in a directory structure of ../ com/ slicepages/ tutorials.

A package statement (pair of curly braces) should enclose import statements and class statement. A class file can contain any number of import statements. We should start with importing one or more class definitions from packages, if this is required. We don’t need to import anything in this tutorial.

package com.slicepages.tutorials {
   //import statements
   public class Profile{}
}

3- Class statement

Class statement defines the name of the class. You should choose the class name carefully which tells the purpose of your class. Also, your class file name is the same name with .as extension. A class must be specified as “public” in order to create instances of that class (except in a few special circumstances). The public modifier makes it possible to access your class via Timeline scripting within Flash file. That statement encloses class contents in its own pair of curly braces.

package com.slicepages.tutorials {

   public class Profile{
      //content of class declaration
   }
}

4- Constructor function

A custom class should always have a constructor function within its curly braces. Don’t worry if you do not define it as the function is created automatically at compile time. Constructor function or construction method is a special method which is named after class name. The name of constructor function is same as the class name. This function is fired when an instance of the class is created. That means the function statements work as setup operations, and executed every time an instance is created.

      //Constructor Method
      public function Profile(yourCountry:String = "Philippines"){
         country = yourCountry;
         trace("Welcome, you are from "+country);
      }

The function is defined as “public” and it returns no value. You cannot call the constructor function by your ActionScript code directly but it’s called when you create an instance of your class, within from FLA file (as you see in this tutorial). At compile time, it actually returns a value to machine code but you cannot specify it. This is why, you should not specify a return value data type to constructor method, not even void.

In this tutorial, constructor function takes one string parameter and a value Philippines is assigned to it. This value is assigned within class definition and remains default value. Private variable country is assigned the value of yourCountry and trace function displays the String value in Output Panel.

5- Add properties to your class

      //define Properties
      public var userName:String;
      public var birthYear:Number;
      private var country:String;

I have defined three properties here. Two of them are public and the remaining one is private. The two properties “username” and “birthYear” are public; you can access them outside the class definition or from within the FLA file but “country” is private and only accessible within class definition. Copy full code —

package com.slicepages.tutorials {

   public class Profile{

      //Constructor Method
      public function Profile(yourCountry:String = "Philippines"){
         country = yourCountry;
         trace("Welcome, you are from "+country);
      }
      //define Properties
      public var userName:String;
      public var birthYear:Number;
      private var country:String;
   }
}

6- Add methods to your class

   public function getProfile(){
      trace("Profile created: "+userName+", "+yourAge()+", "+country);
   }

I have defined a method getProfile() as public above, which display your full profile in Output Panel, if you access it after assigning values to instance variables.

   var myDate:Date = new Date();

   private function yourAge():Number{
   var currentYear:Number = myDate.getFullYear();
   var age:Number = currentYear - birthYear;
   return age;
   }

There is also a second method defined as private and comes after instantiation of an ActionScript 3 class ‒ date class. The custom method yourAge() is using getFullYear() method of date class to assign a four‒digit number to variable currentYear. You should create a Date object first, to access its getFullYear() method. Please note that the variable currentYear is defined within function only.

The method getFullYear() returns full year of Date object, according to local time. Local time is determined by the operating system on which Flash Player is running.

I have defined one more variable age to store a numeric value represented by the expression currentYear ‒ birthYear. The age variable is a Number data type variable and the function returns its value. Note that the variables currentYear and age are neither public nor private. They are defined within function yourAge() and not accessible outside the scope.

Complete ActionScript 3 class file —

package com.slicepages.tutorials {
   public class Profile{

      //Constructor Method
      public function Profile(yourCountry:String = "Philippines"){
         country = yourCountry;
         trace("Welcome, you are from "+country);
      }

      public var userName:String;
      public var birthYear:Number;
      private var country:String;

      public function getProfile(){
         trace("Profile created: "+userName+", "+yourAge()+", "+country);
      }

      var myDate:Date = new Date();

      private function yourAge():Number{
      var currentYear:Number = myDate.getFullYear();
      var age:Number = currentYear - birthYear;
      return age;
      }
   }
}

7- Create FLA file to use the class

Create new Flash file (ActionScript 3.0) and save it as create_profile.fla in order to use the ActionScript 3 class file. Make sure the Profile.as file is in the said directory path structure relative to your Flash document (the FLA file). The folder containing the create_profile.fla should have a com folder in it and your ActionScript 3 class file should be relative to your working folder.

../create_profile.fla
../com/slicepages/tutorials/Profile.as

Next, we need to import our Profile class into the FLA file, so that Timeline Actions could make access to it. Timeline Actions include “creating the Profile object”. Let’s see how …

8- Write an import statement

With the keyframe on Frame 1 selected, open the Actions panel to write an import statement. If you want to use an ActionScript 3 class that is inside a package, you must import either the package or the specific class.

//either this
import com.slicepages.tutorials.*;
//or this
import com.slicepages.tutorials.Profile;

The first import statement imports the entire package, that is importing all ActionScript 3 class files from the package. The second import statement imports the single class by name from the package. However, you must use any one statement and each of them would be importing one available class in this tutorial.

9- Instantiating a Profile object

After importing the Profile class, you can easily create a Profile object. Creating an object involves constructing an instance of the class using ActionScript. First you need to create a variable named someProfile which is data-typed as an object of Profile class. Use var keyword –

// you declare a variable whose data type is your class
var someProfile:Profile

Then you use the constructor method new Profile() to instantiate the object. When you instantiate the Profile object, you also assign it to a variable of Profile data type to store the object. Use new keyword –

//Use constructor method to instantiate an object of your class
someProfile = new Profile();

If it seems all difficult to understand the above description, you can move on without spending much time here. Save your FLA file after entering above codes and test your file. Output Panel displays Welcome, you are from Philippines. This is because constructor function has been directed to do so and this function is fired automatically at the time of object instantiation.

output panel message

Welcome, you are from Philippines. Photo by Randy Lemoine. View license CC BY 2.0


Note that Philippines is the default value which has been defined at the time of function definition. However, it’s better to combine two lines into one to instantiate a Profile object. This time I will pass an argument Poland to constructor method to create the Profile object. This removes the default value Philippines.

//Instantiating a Profile object
var someProfile:Profile = new Profile("Poland");

10- Accessing methods and properties

Add more script to main Timeline to access properties of created Profile object.

someProfile.userName = "Erik";
someProfile.birthYear = 1980;
someProfile.country = "Philippines";

Test your movie to get an error message . I tried to access country property here to make you realize that this is a private property and its scope is limited to class file. Convert this line to comment to avoid its execution at compile time. However, you can easily access other properties and assign values to them.

someProfile.getProfile()
//someProfile.yourAge()

flash movie test
Access to custom method getProfile() to view full profile in Output Panel. Note that you cannot access private method yourAge(). This is defined to be used by getProfile() method within the scope of class definition.

Basics of ActionScript 3 class »

Download CS3 source files

External Links » Read more on this topic

Writing ActionScript 3 class
Actionscript 3 Classes in Flash

Ad

0 comments