`

Monday, September 13, 2010

Creating a Custom Class

An ActionScript class is basically a text-basedfile with an .as extension
stored somewhere onyour computer, containing ActionScript code.
This code works as the blueprint for an object. Let's see what that
blueprint looks like:

package
{
public class CustomClass
{
public function CustomClass()
{
// Tracing some output..!
trace("My CustomClass is Working..!");
}
}
}


On the first line, you'll find the package statement, followed by an
opening curly bracket and ended with a closing curly bracket at the
bottom of the class. Packages are a way to group classes together
and represent the folder in which you saved the file. Imagine you
have created a folder called com inside the same folder where
you've saved an FLA or inside a defined source folder. In order
to have access to the folder and its classes, you will need to define
the package using the folder's name as shown next:

package com {
...
}


This works the same way for subfolders. Let's imagine a folder called
google has been added to the imaginary folder. The package definition
for classes inside this subfolder should then look like this:


package com.google{
...
}


After the package definition, you'll find the class definition, looks
as follows.


public class CustomClass
{
...
}


The name of the class must be the same name as the class file. In this
example, the file needs to be saved as CustomClass.as

At the top of the class definition you'll see the word public, which is a
keyword defining that the class is accessible to all other code in the
project. This keyword is called, an access modifier.

The defined name of the class will be used to instantiate new copies of
the class. Instantiating this class could be done like this:

var myCustomClass:CustomClass= new CustomClass();

After that we see the creation of a new function called CustomClass in
the class. Functions that have the same name as the name of the class
are known as constructors.

public function CustomClass()
{
// Tracing some output..!
trace
("My CustomClass is Working..!");
}

Constructors always have a public access modifier and are called
automatically each time the class is instantiated. This means that
the code inside this function will be executed automatically.

1 comment:

Anonymous said...

Nice post very useful..! keep it up.