05. Scope and "this"
The keyword this is optional, although it is probably better to keep
using it for scope clarity. When a local variable and a class property
share the same name, you must use this when referring to the class property.
The following example demonstrates this.
- Select File -> New (Ctrl-N) and choose ActionScript File
from the New Document dialog. (If you cannot see this file type, you
are running Flash MX 2004 Standard, not Flash MX 2004 Professional.
The standard version does not contain a built-in ActionScript editor
for editing AS2.0 classes. You can use any external editor (including
the standard text editor that comes with your operating system.)

- Save the file in your working directory as ScopeTest.as. As mentioned
earlier, the name of your file has to match the name of the Class that
the file contains.
- Enter the following code:
class ScopeTest {
private var myVar:String = "I am the class property!";
public function doTest(Void):Void {
var myVar:String = "I am the local variable!";
trace ("myVar = " + myVar);
trace ("this.myVar = " + this.myVar);
}
}
- Save your class file.
- Create a new Flash Document (File->New; Ctrl-N) and save
it in your working directory as scopeTest.fla (make sure you save it
in the same directory that you saved ScopeTest.as to).
- Enter the following code on Frame 1 of Layer 1:
var myTest:ScopeTest = new ScopeTest();
myTest.doTest();
- Test your movie (Control -> Test Movie; Ctrl-Enter) and notice
the traces in the Output window.


|