Home > Dev > The Confusion about 'this'

The Confusion about 'this'

I often browse through code libraries written by others and can’t deny noticing that so many developers are making exaggerated use of the ‘this’ keyword in their code. Today I came across CASAlib an otherwise very neat and certainly helpful library and after roaming through some of the code base it turns out that in most classes they’ve put ‘this’ in front of every single class property.

It seems that many newcomers to ActionScript still don’t understand the use of ‘this’ and that it’s only really necessary in rare cases, for example if a method parameter has the same name like it’s relative class property or in a few scope-related situations. It’s also good to have ‘this’ at hand if a dynamic property of a class needs to be accessed (this["foo"]) but other than that please do all a favor and throw out those unnecessary ‘this’! Ban it, lock it in your basement and don’t let it out unless there’s really a need for it!

Categories: Dev Tags: , , ,
  1. cwarnock
    December 5th, 2008 at 14:33 | #1

    Agreed.

    The only reason I can think of as to why people used ‘this’ so much was maybe they put it in when cleaning up their code to make things very explicit.

    Either way, still unnecessary.

  2. December 5th, 2008 at 14:41 | #2

    cwarnock, might be but I actually believe that putting ‘this’ everywhere makes the code look a lot less readable.

  3. December 5th, 2008 at 14:47 | #3

    Agreed. The use of it, is leftover baggage from earlier versions of AS, right?

  4. valyard
    December 5th, 2008 at 14:56 | #4

    in flex when you type this. you get list of methods and properties. I use this only for this.

  5. December 5th, 2008 at 15:57 | #5

    There was some weird scoping issues in an older flash (5? 6?) which meant that “this” was necessary more often than it should have been… I guess some people just got in the habit back then and haven’t got out of it yet…

    @valyard, can’t you just press Ctrl+Space with nothing typed to get the list? That’s how it works in FDT and I think that’s how I remember it working in Flex Builder…

  6. Macaca
    December 5th, 2008 at 16:27 | #6

    We made using this our code standard: it improves code readability enourmously. It’s makes it very clear whick variables are parameters, local variables or class (instance) members, and without using all kinds of ugly/cluttering prefixes or naming schemes. Also it’s better to instantly ‘see’ what is going on -> ‘this or that?’, it makes for a more natural language readable code. A property is a property of a specific object reference (this object of that other object): if you dont use it you have to mentally check for each variable if it’s a member or not.

  7. December 5th, 2008 at 18:02 | #7

    Macaca, I use the underbar prefix for class properties. this is my way to distinct them from local vars and I don’t think this is ugly but as always tastes are different. I can’t see however where ‘this’ makes code more readable. For me it’s just redundant luggage. If you type a property without this in front of it, it becomes also clear that the object belongs to the class.

  8. December 5th, 2008 at 23:30 | #8

    I use the underscore prefix convention for class properties as well, however, I only use it for private or protected properties. While I often have getter/setters for public class properties, there are the occasions where I use a public class property. In instances where I do, the property has the same format as a locally scoped variable defined in a method or passed in as an argument, in this scenario I would agree that the “this” keyword can be a helpful code clarifying addition.

  9. December 6th, 2008 at 01:35 | #9

    Like others have said, I’ll typically use an underscore for class properties. The only time I consistently use “this” is in classes that extend class like MovieClip. I’d use this.gotoAndPlay() or this.currentFrame rather than leaving it off.

    That could be a throwback to when I first started coding, who knows. That’s just what I do…

  10. December 12th, 2008 at 06:37 | #10

    I don’t use this out of laziness (more typing necessary). Also, I tend to think that if you’re confusing local and class variables, your class might be too large…

  11. Ihsan
    December 20th, 2008 at 21:57 | #11

    IMHO, “this” is a tool which should not be abused. The unnecessary use of ‘this’ is code crippling.

    For example see PHP 5 class sources, in which the use of ‘$this’ is mandatory, simply the code looses its beauty and readability… (Since php is an interpreter $this clause makes it work faster, so there is at least some logical reason…)

    There are rare places to use ‘this’ in AS3. ‘this’ is handy for some implementations of Proxy subclasses, where defining ways of multiple access to the fixed and virtual (such as dynamic properties, functions or members with ownership relations etc) properties and methods. So when writing an iterator function proxy, such as flash_proxy nextValue, this[] directly uses the flash_proxy getProperty which is saving extra coding overhead.
    Also if you save/load the persistent object states in non standard AS3 ways, you may need to use this keyword as accessor root to your object since there is no other common way.

    The (ab)use of ‘this’ can be easily avoided by rule 1 I stated below…

    I am coding since 1982 (yes I am 40 now, old programmers never die, they just recurse…). What I learned : Safe coding is an art of building good habits. Here are some of the rules:

    0) Always use remarks. So a month later you can still understand what (the hell) the code is about. And make a standard notation for your remarks. For instance before every function or method, write TASK: methods task, and ARGS: explain parameter use…

    1) Use naming conventions… So with a glance you can understand what kind of (monsterous) thing it refers to. ( just a joke : Namespaces came out of clumsy people who can not manage to do this :) )
    For instance starting
    a) class names with letter t or c, tMyObject.
    b) class protected vars with _ or f or p, _pos, fpos,ppos.
    c) public names always with lowercase, word boundaries capital, myPublicProperty etc…
    d) constants always in capital, MYCONST = 2.
    Etc. etc…create your own standard or use some others.

    2) Be lazy. Code optimally. First decide how to modulerize your code and find cross benefiting modules. So this will make you write non redundant code without unnecessary crowd of functions methods and classes.

    3) Try using native structures of the language you write first. If you feel that it is a dead end then go and re-invent the wheel.

    4) Do not forget what you are doing. First finish implementing your program, then you can make fancy add ons to it if there is time.

    5) Do not write cryptic code.
    Write
    v = ++i;
    if(v>5)doThat();
    Instead of
    if((v=++i)>5)doThat();
    So that will make you, others and even the interpreter or compiler understand your code easier.

    6) If the language does not imply a source file convention create your own.

    7) Before making “revolutions” back up your sources to somewhere safe… :)

    ok.ok… There are other things to share but it goes so far off topic. Thanks anyway.

  12. WORMSS
    December 30th, 2008 at 01:36 | #12

    I have to write this. due to there are multiple people sharing the same code/classes, its just the standard we have came up with…

    but I am interested in this [crippling] concept someone said above?…

    It was my understanding that doing this.varName would be better due to not having to check if there is a local scope variable within the function and it would just go directly to the class varName ??

    Mind you, I think you guys may actually hate some of the things I do to my personal classes..

    this.CONST_NAME [static/class public/private const]
    this.varName [class public var]
    this._varName [class private var]
    __varName [local scoped var]
    ___varName [local scoped function var]

    EG:
    private function funcName(__arg) {
    const __localFunc = function(___arg) {
    do something that gets called from multiple places but only within this function
    }
    }
    I just find it easier to know the more underscores the more private it is.
    I have yet to ever go beyond three underscores, and my work mates have seen this and think its a little crazy, but it only takes a glance to easily my way of thinking and then it becomes very easy to read… [I can't see them ever adopting it tho]

  13. Ihsan
    December 30th, 2008 at 18:42 | #13

    Hi WORMSS,
    As long as you code in as3 there is no problem. But for general programming habits, I do not recommend use of leading underscores. Because many interpreters which have the sources in c or cpp traditionally introduce “gizmo” or “magic” functions, variables, classes, methods and properties with leading underscores. Why is that? I really do not know :).

  14. January 5th, 2009 at 20:12 | #14

    Totally agree! We have made our code standards also to use this. But i’m the only one who’s doing it without wanting it.
    It makes stuff less readable, and besides that it’s anoying!

  15. February 26th, 2009 at 03:11 | #15

    You can take my this keyword away from my cold dead hands, my friend. I’m not a newcomer either. I’ve been writing code in various languages since 2000 and doing it in several versions of Flash since 2004. Using this everywhere makes code way more readable for me. I know instantly the scope where everything is located. If I come back to a class I haven’t touched in a week or a month, I don’t have to think to myself (even for the nanosecond it takes), “is that a local variable, or is it a class member?” Underscoring only differentiates some of the members, and the only benefit I use it for is to know when something is a private variable. In addition to instantly knowing the scope, using this for code hinting gets my code onto the screen faster. Sure, I could hit ctrl-space in most editors to bring it up, but why do that for one special case when I only need the dot for everything else? In short, skipping this would only slow me down and make it harder to do my job. I don’t care if it’s “not necessary”. I want to keep my mind on getting the problem done, not trying to understand my code.

  16. Ihsan
    February 26th, 2009 at 17:21 | #16

    Dear Josh,
    In Turkish we have a proverb which says “every brave warrior has his own way of eating yoghurt” in summary :).

  17. February 26th, 2009 at 22:07 | #17

    Josh wrote:

    “Using this everywhere makes code way more readable for me”

    and:

    “I want to keep my mind on getting the problem done, not trying to understand my code.”

    A little contradictory aren’t we?!

    Note: ‘this’ is not only not necessary, it is bad practice! ;)

  18. February 27th, 2009 at 11:06 | #18

    sascha, those statements are not contradictory. Let me rearrange my thoughts to explain: When my code is more readable, then I’m not spending more time trying to understand it again, and I can get the problem solved faster. I believe “this” makes my code more readable, so I believe that I get my problems solved faster.

    I’ve noted that you use underscores to do the same task that I use “this”. What makes your approach better? Underscores are an optional style choice (that is often frowned upon in other languages, I might add), but the “this” keyword is a construct available as part of the language itself. It sounds to me like you are reinventing the wheel by using underscores. Bad practice, indeed.

    Let me finish my argument by noting that I can make the same argument as you. The use of underscores is not necessary. Clearly then, the only acceptable approach is to ensure that no variables that may accessible in the same function without a qualifier should share the same name.

    I don’t want to do that, and I don’t think you do either. :)

  19. Dan
    March 8th, 2009 at 19:05 | #19

    Couldn’t agree more with Sascha.
    “this” everywhere reminds me of people moving their lips when reading a newspaper. ;)
    How can typing more make code cleaner? If you need “this” to distinguish between this and that your class maybe suffers from feature envy.

    But it’s funny, few things stir up a debate as heated as when it comes to coding conventions and which is the best editor.

    Cheers, Dan

  20. Ihsan
    March 9th, 2009 at 19:14 | #20

    Gee, people, we are not choosing religions here.
    “this” is just a tool. It has its uses. Use of it is not and should not be a “choice” but on “purpose”. So I agree with everyone against abuse of it.

    As : this.cripples, this.code, this.really.
    :)
    When coding just for him/herself, one may do anything he/she wishes. But for writing human-readable code (the main purpose of computer languages) which is understandable by other poor human beings like us, the main point is being clear.
    Abuse of any coding structure is generally categorized as SOURCE OBFUSCATION.
    Abuse of “this” goes into that category IMO.

  21. P.J. Onori
    April 24th, 2009 at 04:31 | #21

    I use ‘this’ almost all the time, but only to prompt Flex to code complete. Over the long run, adding ‘this’ saves me a lot of time and typos.

  22. August 3rd, 2009 at 22:55 | #22

    I remember that “this” used to be a good practice in the old days of as2, but that was a long time ago.
    For the people who said they use “this” just to prompt Flex code complete, you can always use CTRL+space.

  23. warappa
    February 19th, 2010 at 08:00 | #23

    Hi,
    ever tried to write “this” in an anonymous function? This becomes “global” and not your class. Therefore using “this” would lead to an incorrectly behaving code…

    Try this (*g*) in the constructor of a Flex app (or with ANY other anonymous event handler):

    addEventListener(FlexEvent.CREATION_COMPLETE,
    function(e:Event):void
    {
    trace(“this: ” + this);
    });

    Just my 2 cents

    Lg
    warappa

  1. No trackbacks yet.
You must be logged in to post a comment.