I think the best post I've seen about the this keyword is the one here
by Mike Winter:
<URL:
http://groups.google.com.au/group/comp.lang.javascript/browse_frm/thr...
The first part is about closures, the second part on this is
excellent.
With regard to the second part only, and in spite of many excellent
posts that Mike contributed, this one doesn't quite make that rating
in my book.
The first problem is the use of the term "this operator" which, quite
remarkably, also seems to have found its way into Mozilla JS 1.5
documentation:
<URL:
http://developer.mozilla.org/en/docs/
Core_JavaScript_1.5_Reference:Operators:Special_Operators:this_Operator>
"this" in Javascript is not an operator, it is a (read-only) variable
and can be used as any other variable operand of type
"object" (although, as it is read-only, it cannot be directly assigned
within the program).
"this" can implicitly given a value, with the most direct implicit
assignment being attained through the function.prototype.call/apply
methods. Nonetheless, in the most common usage, "this" takes it value
initially as a reference to the global object, and automatically
changes as execution contexts are created (and restored) for method
calls in accordance with the way in which the reference to the method
was designated.
If the reference to the method is obtained without use of dot or
bracket notation, "this" is assigned a reference to the global object.
On the other hand if dot or bracket notation is used to arrive at the
reference, "this" is assigned the object at the end of the accessor
path that leads to the reference.
In other words, a function invoked as f(...) will have a "this" value
of the global object, whereas a.b.c.f(...) would have a "this" value
of c.
Perhaps most non-intuitive in the above is that the above paragraph
applies even when an inner function is called, where one might expect
the "this" value to be preserved (as it is when code under the eval
function is invoked).
So the second problem with Mike's post is that it over-complicates the
description of what one should expect of the "this" value to be by
involving the variable object, scope chain and the "new" operator[1]
in the description.
See "Objects and this" at
<URL:
http://javascript.crockford.com/survey.html>
for a much more succinct, easy to grasp, description.
[1] The new operator relationship to "this" is really just a special
case of function.prototype.call (performed internally) of the
constructor function.