Category Archives: AS2

This is a good time to use ‘this’

I know for a lot of actionscript coders out there, especially beginners, ‘this’ in can be rather confusing. This issue can spark some pretty heated debates about this proper use. So before diving in here is a short explanation of ‘this’. In actionscript the object the code is currently running in is referred to as ‘this’. So lets say a class has a property myVar, putting this.myVar tells actionscript to look in the current object for the property myVar. Why do we need this? This doesn’t make any sense! Well look at the code below:

?View Code ACTIONSCRIPT3
1
2
3
4
5
6
7
public var age:Number;
 
public function myClass(age:Number)
{
   if(age > 0)
      this.age = age;
}

So lets say this is a class (myClass) with a public variable age. In actionscript you can declare local variables and parameters that only exist for the duration of the function. These local variables have the smallest scope, but have the highest preference, meaning if another variable is named the same the local variable, the local variable will be used instead of the class variable. In the above example we have a constructor the class myClass. Can you see were I am going with this? In the above constructor we have two age variables! The parameter is defined in the function. So to set the class variable we need to use ‘this’ to specify between the local variable and the class variable.

This example is the only the real time that you need to use ‘this’, of course this is only my opinion. What do you think? Coding vets how do you feel about ‘this’?