On Thu, Dec 30, 2010 at 10:02 AM, Peter van der Zee <[email protected]>wrote:

> On Thu, Dec 30, 2010 at 2:48 PM, Tom Wilson <[email protected]> wrote:
>
>> I just finished reading "High Performance JavaScript" and now I'm paying
>> more attention to scope. So my question is: within an object method, is
>> there any benefit to declaring a local variable referencing 'this'? Is that
>> just redundant? What about a local variable referencing a property of 'this'
>> that is itself an object? Like var myLocal = this.someProperty so that you
>> can refer  to myLocal.x, myLocal.y, etc.
>>
>>
> The short answer is "no". This, in terms of speed, `this` is equal to a
> regular variable. Making an alias is only going to cause (more?) confusion.
>

The advantage might be made up by producing leaner code though, especially
if you use a minimizer (like YUI Compressor).  For example, suppose your
code does this:

function foo() {
    if (this.someProperty === "foo") {
        // ...
    }
    if (this.someProperty === "bar") {
        // ...
    }
}

When minimized, "this.someProperty" can't be replaced because it's not
specific to the function scope.  However, if you did something like this:

function foo() {
    var someProperty = this.someProperty;
    if (someProperty === "foo") {
        // ...
    }
    if (someProperty === "bar") {
        // ...
    }
}

The code is still readable, and you've saved 5 characters ("this.") per
usage.  In that example above, I've added more characters than I've removed,
however, it depends on what you name your property and how many times it's
used.  And when minimized, that's when the real savings come in because the
minimizer can replace the "someProperty" variable with a single character.
 In which case you might end up with something like:

function foo(){var A=this.someProperty;if(A==="foo"){}if(A==="bar"){}}

Had you minimized the original version, it would look more like this:

function
foo(){if(this.someProperty==="foo"){}if(this.someProperty==="bar"){}}

Regards,
Peter Foti

-- 
To view archived discussions from the original JSMentors Mailman list: 
http://www.mail-archive.com/[email protected]/

To search via a non-Google archive, visit here: 
http://www.mail-archive.com/[email protected]/

To unsubscribe from this group, send email to
[email protected]

Reply via email to