So in the last post we looked at some of the very basic things about AS classes. In this post I am going to go a bit further and take a look at an example of basic class.

So in the last post we examined basic class structure such as (examples in this post are AS 2.0 syntax)

class SomeClass {
function SomeClass(){

}
}

This is as simple as a class can get and this class would not actually do anything. So lets take a look at a class that actually does something (all be it something useless and simple)

The following would go in an external actionscript file named Person.as. For simplicity sake it would be saved in the same folder as the FLA (setting up class paths will be in another post. For a primer on setting up class paths see http://www.flash-mx.com/flash/actionscript_lott2.cfm. Look here is nothing happens when you test the following. I had to tweek the class path in flash 8 to get this to run).

class Person {
// example instance variable
var _myName:String;
//constructor function
function Person(myName:String) {
_myName = myName;
trace("New Person");
}
//example method
function sayHello() {
trace("Hello, my name is "+_myName);
}
}

Then in Flash use the following code on an actions layer in the first frame:

var person = new Person("Bill");
person.sayHello();

When you test the movie, you should see the following in the output window:
New Person
Hello, my name is Bill

Here we saw the use of the keyword new followed by the name of the function and in this example we passed a string as the parameter (myName:String). The constructor (the function with the same name as the class and the AS file) is automatically called and executes any code in its body. In this case, it is setting an instance variable _myName (a standard coding convention is to place an underscore in front of instance variables to avoid naming conflicts).

The next line:
person.sayHello();

calls the sayHello() function of the person instance which causes the following function in the class file to execute:

function sayHello() {
trace("Hello, my name is "+_myName);
}

so we have done several things. First we created an instance of the Person Object (class) and in doing so we set the instance variable _myName to the value passed to the constructor function. Then we called the sayHello method.

Now that we have this basic class set up, we can create multiple instances. For example:

var bill = new Person("Bill");
bill.sayHello();

var jane = new Person("Jane");
jane.sayHello();

var sam = new Person("Sam");
sam.sayHello();

Would output:

New Person
Hello, my name is Bill
New Person
Hello, my name is Jane
New Person
Hello, my name is Sam

So here we can see that with the same class (object) we can assign different properties and call methods on several instance of the same class which all originate from the same AS file (object/class).

That's all for now.