AS1 OOP: Object Scope
by senocular
The this Keyword
In Actionscript this represents what can be considered the
current scope. If you putting code in a timeline, say _root,
then using this will allow you to reference _root directly.
For a function, if the function is defined in _root, the
this keyword will again reference _root. If the function was
defined in some generic object created in _root, this in
that function would be the generic object.
Lets add a function to an array object. Using this, we
can access that array directly, and in doing so, use the
function to alter the array’s contents.
- myArray = [1,2];
- myArray.switchValues = function(){
- var temp = this[0];
- this[0] = this[1];
- this[1] = temp;
- };
- trace(myArray); // traces 1,2
- myArray.switchValues();
- trace(myArray); // traces 2,1
As you can see, this function uses this to directly
access the current object’s (myArray’s) array elements as
this refers to the array itself. Then, using a local
temporary variable temp, it is able to internally switch the
two values of those array elements. The trace after the
function call confirms its success on the myArray variable.
Even though the this keyword references the current
object, a this in a function may not always reference the
same object. Since function variables are references to a
function object, there can be separate definitions of the
same function in different objects. Depending on which
object initiates that function call determines which object
the this in the function represents. This behavior is quite
advantageous as it can save you the need to repeatedly
redefine the same function for multiple objects. Instead,
you can define the function once and then assign it to each
object requiring it. For example
- increaseNum = function(){
- this.num++;
- trace(this.num);
- };
- objectA = {num: 0};
- objectA.increaseNum = increaseNum;
- objectB = {num: 10};
- objectB.increaseNum = increaseNum;
- objectA.increaseNum(); // traces 1
- objectB.increaseNum(); // traces 11
Here, two separate objects, objectA and objectB each have
their separate num values assigned to them. Each also have
assigned to them a increaseNum property which is set to be
the previously defined increaseNum function. When
increaseNum is run for each, the this object in the function
block refers to the object which called the function. It’s
the same function, only the this value is representative of
what object called it.
The this keyword is used in excess when dealing with
objects and functions, or methods, associated with such
objects. Each method of an object gains access to that
object through the use of this so be prepared to write it
consistently especially when writing methods to be used with
all instances of an object type.