coder and technology lover
We should always use Actionscript’s "this" keyword
I was wondering if to use or not the “new” keyword for classes variables and methods, because it’s not mandatory and in as3 examples is rarely used and when it’s used, is only to avoid name collisions (typically when setting a class property using a given argument), such:
package {
public class MyClass {
private var myVar:uint;
public function MyClass(myVar:uint) {
this.myVar = myVar;
}
}
}
However there are 3 valid reasons to (always) use the “this” keyword:
- Is an excellent way to visually differentiate between static and dynamic variable (static variables can’t use the “this” keyword, otherwise you get a compile error)
- When invoking methods is immediately evident which is the class owner/target of the method itself
- Faster typing and developing thanks to Flex Builder hints (after typing “this.”, I can select all the applicable methods, which is faster and error free than type the entire method name)
This entry was posted on 7, Wednesday f, 2009 at 4:52 pm, and is filed under actionscript. Follow any responses to this post through RSS 2.0. You can leave a response or trackback from your own site.


4, Wednesday f, 2009 - 7:08 am
Amen! It’s amazing how many people are out there lacking the insight of using this keyword. It also provides insight into where variables are defined:
[code]
package {
public class MyClass {
private var myVar:String='some text';
public function MyClass():void {
this.myVar; // using "this" shows the variable is a member of the class.
var someOtherVar:String = 'some other text';
someOtherVar = this.myVar; // not using "this" with someOtherVar shows the variable is declared within the method, either as an argument or defined locally.
}
}
}
[/code]
This is just something everyone should know and use. It also makes code a lot friendlier for others using the same file.
27, Wednesday f, 2010 - 1:44 pm
i think this is a very good jobe n examples