AS3-101: Intro to Functions Part 2 and Class Overview

– taterboy | September 26th, 2009

Filed under: ActionScript 101, ActionScript 3, Flash, Flex, Tutorials

The Class:
Classes are a collection of variables and/or functions that provide unique functionality. Within a class, functions and variables define the functionality and how that functionality can be expanded or used by other classes or components. In AS3 a class is wrapped inside a package, a class must be public and have a public constructor(function) by the same name.

?View Code ACTIONSCRIPT
package{
	public class FunctionTester{
		public function FunctionTester(){
			//constructor, runs after class is loaded, but before visual elements are loaded.
			//classes and their constructors must be public
			trace("load");
		}
	}
}

Inside the package brackets is where the class is declared and all other classes are imported, also meta information can be placed at this level. Everything else is part of the class and must be contained within the class brackets.

?View Code ACTIONSCRIPT
package{
	//import other classes here.
	import flash.events.Event;
 
	//add metadata if needed
	[Event (name="TESTER_EVENT", type="flash.events.Event")]
	public class FunctionTester{
		public function FunctionTester(){
			//constructor, runs after class is loaded, but before visual elements are loaded.
			//classes and their constructors must be public
			trace("load");
		}
	}
}

Within the class brackets there is no rule about how variables and functions are organized but this is how I do it, based on what I have seen most others do.

?View Code ACTIONSCRIPT
package{
	public class FunctionTester{
 
		// class constant or config variables
 
		// class properties, things that change
 
		//private variables
 
		//setters and getters
 
		public function FunctionTester(){
			//constructor, runs after class is loaded, but before visual elements are loaded.
			//classes and their constructors must be public
			trace("load");
		}
 
		// constructor based functions, load or called when the constructor executes
 
		// all other functions that are the main functionality of the class
 
		// event handlers
 
		// utilities, small functions that are used by everything else.
	}
}

Private, Public, Protected and Static:
You may notice in class files or in flex, functions and variables need to be scoped to a namespace. This basically tells the compiler if other classes will see or have access to a function or variable within the class.

Here is a simple class file with a few functions that are scoped to internal and external namespaces, that way we can see what all this jargon really means to us and our applications. Copy the following code into a new .as file called “FunctionTester.as”. place this file next to the fla or inside a new Flex Project src folder.

?View Code ACTIONSCRIPT
package{
	public class FunctionTester{
 
		public function FunctionTester(){
			//constructor, runs after class is loaded, but before visual elements are loaded.
			//classes and their constructors must be public
			trace("load");
		}
 
		private function testPrivate():void{
			trace("I am private");
		}
 
		public function testPublic():void{
			trace("I am public");
			testPrivate();
		}
 
		protected function testProtected():void{
			trace("I am protected");
		}
 
		public static function testStatic():void{
			trace("I am static");
		}
 
	}
}

Now to can create an instance of the FunctionTester class using this line.

?View Code ACTIONSCRIPT
	var test:FunctionTester = new FunctionTester();

Private:
Private functions or variables are not accessible or even visible from outside the class. so if we call this method, the compiler will error out. There is nothing we can do about this, the function is private and can only be accessed by code that is inside the class. It is good practice to only scope things as public if they need to be, making everything public “just in case” can be confusing to others trying to understand the functionality of your class or component.

?View Code ACTIONSCRIPT
	test.testPrivate(); //compiler error

Public:
This method call works as expected, it is scoped to be accessed through the instance of the class. You will also notice, this public method executed the testPrivate function from within the class.

?View Code ACTIONSCRIPT
	test.testPublic(); //I am public // I am Private

Protected:
Protected functions are very similar to private functions, in that they are not accessible to the outside of the class. What protected functions offer is the ability to expand or overwrite this function by extending the FunctionTester class. If we create a new class that extends the FunctionTester class, we will have access to the testProtected function in this new class, but we will not have access to testPrivate. A private function is not inherited. We will also have the ability to overwrite the testProtected function in the new class if we need to change some of the functionality.

Static:
Static is used when we want to use a class as a singleton instead of an instance. A singleton means we access all the properties and methods directly through the class itself, not an instance of the class. Events are an example of a class that uses both static and public variables in the same class.

?View Code ACTIONSCRIPT
FunctionTester.testStatic();

Setters and Getters:
Setters and Getters are the way to turn functions into class properties. Unless you are building classes or components that are portable, you may not have need for them. Honestly, I constantly find using them confusing, there is a fine line when they are the right thing to use opposed to just using a variable or function instead. I will try to run through a few uses for each.

You can copy the code below into the same FunctionTester class file from above.

?View Code ACTIONSCRIPT
package{
	public class FunctionTester{
 
		private var _status:String = "";
		public function set status(str:String):void{
			_status = str;
			trace("set status");
		}
		public function get status():String{
			trace("get status")
			return _status;
		}
 
		public function FunctionTester(){
			//constructor, runs after class is loaded, but before visual elements are loaded.
			//classes and their constructors must be public
			trace("load");
		}
 
		private function testPrivate():void{
			trace("I am private");
		}
 
		public function testPublic():void{
			trace("I am public");
			testPrivate();
		}
 
		protected function testProtected():void{
			trace("I am protected");
		}
 
		public static function testStatic():void{
			trace("I am static");
		}
 
	}
}

Now create an instance of the class as we did before:

?View Code ACTIONSCRIPT
var test:FunctionTester = new FunctionTester();

Setters:
Setters are a public way to set a private variable. it is a best practice to name a private variable with an underscore as the first character of the name (“_status”); The setter uses the same name without the underscore (“status”).

?View Code ACTIONSCRIPT
test.status = "setters are cool";

With the current use of the setter and getter in this class, it would be easier just to use a public variable instead. Where a setter comes in handy is when you add functionality when a property is being set or you want the property to be write only. It is easier to look at a setter, not as dumbed-down function, but as an enhanced variable/property.

Note: A setter must have an argument.

Note: If you get to a point where you need to send more than one argument at a time or to a setter, you need to use a normal function instead.

Getters:
Also a form of enhanced variable, will return a value. You can add functionality whenever a property is requested, return a modified value, or return a different value type than the setter and/or the private variable.

?View Code ACTIONSCRIPT
var stat:String  = test.status;
trace(stat);

Where To Go From Here:
Working with class files opens the possibilities of what you can accomplish as a developer. You can now write class/components that can be used later to optimize your workflow or to share and contribute to the community. Take some existing code you have created or a snippet from somewhere else and make it into a new class. Try to make this as flexible and optimized as possible. Feel free to share your creations in the comments below.

Technorati Tags: , , , , , , , , , ,

| 3 Comments » | facebook:

3 Comments »

  1. Thanks, good post!
    I knew most of this information as ‘loose bits’, but after reading this post I have a much more clear and complete picture in my head of how classes are coded. It also adds a bit of ‘why’ to the ‘how’.
    So thanks, maybe I’ll finally start using getter/setters, now that I have an idea why. : )

    Comment by Paul — October 1, 2009 @ 12:56 am

  2. Thanks for letting me know you like it, sometimes you put things out there and think, “no one will ever want to read this”. So Thanks.

    Comment by taterboy — October 1, 2009 @ 5:01 am

  3. Great job, thank you for sharing.

    Comment by Sharedtut — February 3, 2010 @ 7:27 am

RSS feed for comments on this post. TrackBack URL

Leave a comment

*