HelloWorld in AS 2.0 - How to write a simple AS 2.0 class
And I mean really simple. No type definitions, no private methods, just the basics. We can worry about the rest later.
AS 2.0 uses self-contained classes instead of stray code on key frames. Each class must be put in its own .as file, and the name of the .as file must match the name of the class. Example: MyFirstClass.as will contain a class definition for the class MyFirstClass. Now that we understand that part, let's write our first class.
A class declaration looks like this:
class ClassName {
// a method of this class
function aMethodName() {
// some stuff here
}
// another method of this class
function anotherMethodName() {
// more stuff here
}
}
So if we want to write a HelloWorld class, we could do something like this:
class HelloWorld {
// the method that says hello
function sayHello() {
trace("Hello World.");
}
}
We already know that we have to save this class as HelloWorld.as. But where do we save it? Anywhere we want. We just have to make sure that the .fla that uses this class, knows where to find it. We will get to that in a second.
First let's create a directory for our classes. How about My Documents/ASClasses/Practice. Save the file in the Practice folder as HelloWorld.as. Now we can create the .fla file that uses the HelloWorld class. The name of the .fla doesn't have to match the class name; it can be anything you want.
The first thing we have to do in the .fla is set the classpath. The classpath will tell Flash where to find the classes. If you are familiar with Java, you should know exactly what I'm talking about. To set the classpath go to File > Publish Settings. On the Flash tab, click on the Settings button next to the ActionScript version drop-down menu. In the ActionScript Settings dialog, click on the plus to add a classpath (you can have more than one). Then click on the icon that looks like this:
Now navigate to your My Documents/ASClasses/Practice folder or wherever else you saved HelloWorld.as. Click OK. This will set the local classpath for this particular .fla.
To create an instance of the HelloWorld class in your movie, put the following:
MyHelloWorld = new HelloWorld();
Then you can call its methods like so:
MyHelloWorld.sayHello();
When you go to Control > Test movie now, the output window should spit out “Hello World.” And that’s it. You have just written and used your first AS 2.0 class.
Next week: What’s the deal with public, private, static and dynamic?





posted
by Vera (