AS3.0 TutBits #01: Getter and Setter

AS3.0 TutBits is a series of small Actionscript mini tutorials. Their purpose is to point out certain differences of the actionscript 3.0 language compared to other programming languages. Each tutorial just concentrates on a tiny technical issue. The AS3.0 TutBits are not tutorials that teaches you how to programm in actionscript.

Ok, enough introductional text - let’s start:

First topic is Getter and Setter. Well, I do no want to start the discussion again if they are useful or not - here it is how they are supported in Actionscript3.0:

package
{
	public class GetterSetter
	{
		private var hiddenName:String = "OLD: Joshua";
 
		public function get name():String
		{
			return this.hiddenName;
		}		
 
		public function set name(newName:String):void
		{
			this.hiddenName = "NEW: " + newName;
		}
	}
 
}

On line #05, we have the class property called hidden name we want to make accessible via getter and setters. Therefore, we create two methods one line #07 and line #12 which are identified by the keyword get and set followed by the same methodname name(). With this construct you create a faked public class property called name of the class GetterSetter. You access it like a normal property using the following syntax:

var gs:GetterSetter = new GetterSetter();
trace(gs.name);
gs.name = "Joshua";
trace(gs.name);

The output of that would be:

OLD: Joshua
NEW: Joshua

That means that when you access the faked class property you actually call the respective get- or set- method. So you have the easiness of simulating direct access of a property value but still have the chance to keep control of it.

Nevertheless, this technique has some drawbacks. First, it is not possible that the property has the same name as the get/set methodname. So, if we would have named our property “name” instead of “hiddenName” it would resulted in a compile-time error. In addition, whenever you call the set method - the get method is called automatically as the result of the set method call. This hidden “feature” could also causes some confusion if you do not know that.

In the end it is up to your personal taste if you want to use this feature of actionscript or not. Of course you could implement getters and setters in the standard way writing methods like getHiddenName() and setHiddenName().


Leave a Reply