Lesson 4
Variables
in this lesson we learn about variables. There are two types of variables: local variables, which are valid only within one function and variables, which we declare at the beginning of a class.
You can see what I mean in the script. The variable test has been defined twice here. However, the class variable is the one declared at the beginning.
package
{
import flash.display.Sprite;
import flash.text.TextField;
public class Starter_4 extends Sprite
{
private var tField:TextField;
public function Starter_4 ()
{
myTest();
}
private function myTest():void
{
var a:Testvar = new Testvar();
a.defTest();
addChild(a);
tField = new TextField();
tField.autoSize = "left";
tField.background = true;
tField.border = true;
tField.x = 15;
tField.y = 15;
tField.text = "test from the getter is: "+a.myVar;
}
}
}
import flash.display.Sprite;
import flash.text.TextField;
class Testvar extends Sprite
{
private var test:String = "I am the variable test.";
private var tsecField:TextField;
public function Testvar():void
{
}
public function defTest():void
{
tsecField = new TextField();
tsecField.autoSize = "left";
tsecField.border = true;
tsecField.x = 15;
tsecField.y = 75;
var test:String = "I am a local testvar and I override the var test here.";
tsecField.text = "Another test: "+test;
addChild(tsecField);
}
public function get myVar():String
{
return test;
}
}
However, if you do not declare test as a local variable within the function defTest you may end up with a different return value for test. I have prepared an example (Starter_10.as). Play with it and you will see what I mean. For now it is time to explain what is public and private, so see the next lesson.