On Thu, 30 Dec 2010 14:48:44 +0100, 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?

It's redundant at best. At worst it can lead to a small slowdown.
The "this" operator is special and will always refer to the same value
during a call, and that value is (in ES3) known to be an object.

That means that usages of "this" can omit some checks that a variable
use would require (e.g. "this.method()" doesn't need to check whether
"this" refers to a primitive value that needs to be promoted to an object).

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.

I would always cache a property that I use more than once, but mainly
for readability. I just don't like repeated subexpressions :)

If there are many references to the same property, it's likely to perform
marginally better to cache it too, but as with most optimizations, you
should measure it first. There will be a slight overhead of an extra local
variable too. If that variable is also captured by closures, it might start
costing as much as the direct lookup.

/L

--
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