Lesson 9

Getter and Setter

Somehow in AS2 getters and setters were not very popular. This may change in AS3, although we can call variables in various ways. We are already familiar with getters, since we have been using them at various occasions throughout the tutorial. A getter is a function with a return value depending on what we return. In our example we return a string. A setter has always one parameter, since we give a variable a new value through the parameter. Check the example below.

The syntax is simple. We first create an instance of the class containing the getter and setter, in our case it is "a". Then we call the setter, if we want to change the variable and using the dot syntax we call the setter function and with the = operator we fill the parameter. To retieve the value for a variable we use the getter in a similar way as shown in the example (a.myVar). Unlike a regular function call we omit the parentheses. Do not forget to add the return type, otherwise there will be an error.

package 
{
	import flash.display.Sprite;
	import flash.text.TextField;
	
	public class Starter_13 extends Sprite 
	{
	       private var tsecField:TextField;
	       private var tField:TextField;
	       public function Starter_13 () 
	       {
	               myTest();
	       }
	       private function myTest():void 
	       {
	               var a:Testvar = new Testvar();
	       
	               tField = new TextField();
	               tField.autoSize = "left";
	               tField.background = true;
	               tField.border = true;
	               a.mynewVar = "This is the new var.";
	               tField.text = "Test is: "+a.myVar;
	               addChild(tField);
	       }
	}
}
import flash.display.Sprite;
import flash.text.TextField;
class Testvar extends Sprite 
{
	public var test:String;
	public function Testvar() 
	{
	}
	public function set mynewVar(newTest:String):void 
	{
	       test = newTest;
	}
	public function get myVar():String 
	{
	       return test;
	}
}

Next is an example for a new feature in AS3, the namespace.

previous  next