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)
| Print article | This entry was posted by Davide Zanotti 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. |
about 8 months ago
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.
about 6 months ago
i think this is a very good jobe n examples
about 2 months ago
But what does ‘this’ refer to?
When you say~ this.myVar = myVar; ~what does that mean?
about 2 months ago
“this” refers specifically to the class instance
about 2 months ago
I still don’t get it, that terminology of instances, methods, etc. is a bit confusing.
Instead of what word was used ‘this’ ?
What would be ‘the wrong’ way to do this, like without using ‘this’ statement.
MyClass.myVar = myar ?
about 2 months ago
First of all, I suggest you the excellent book “Essential Actionscript 3″: http://www.amazon.com/Essential-ActionScript-3-0-Colin-Moock/dp/0596526946/ref=sr_1_2?ie=UTF8&s=books&qid=1273249748&sr=1-2
anyway:
instance: an object created from a class constructor (ie: instance = new Class())
method: a function related to a specific class and attached to the instance (ie: instance.method())
about 2 months ago
Thanx for the book reference.
I found it, I am reading it these days.