http://javascriptweblog.wordpress.com/2010/08/30/understanding-javascripts-this/
Lets start with the ECMAScript definition of this
:
this
keyword evaluates to the value of the
ThisBinding
of the current execution context.
from ECMA 5.1, 11.1.1
How is ThisBinding set?
Each function defines a [[Call]] internal method (ECMA 5.1, 13.2.1 [[Call]]) which passes invocation values to the function’s execution context:
1. If the function code is strict code, set the ThisBinding to thisValue.
2. Else if thisValue is null or undefined, set the ThisBinding to the global object.
3. Else if Type(thisValue) is not Object, set the ThisBinding to ToObject(thisValue).
4. Else set the ThisBinding to thisValue
from ECMA 5.1, 10.4.3 Entering Function Code (slightly edited)
In other words ThisBinding
is set to the object coercion of the abstract argument thisValue
, or ifthisValue
is undefined, the global object (unless running in strict mode in which case thisValue
is assigned to ThisBinding
as-is)
So where does thisValue
come from?
Here we need to go back to our 5 types of function invocation:
1. Invoke as a method
2. Invoke as baseless function call
in ECMAScript parlance these are Function Calls and have two components: a MemberExpression and an Arguments list.
2. Let func be GetValue(ref).
6. If Type(ref) is Reference, then
a. If IsPropertyReference(ref) is true
i. Let thisValue be GetBase(ref).
b. Else, the base of ref is an Environment Record
i. Let thisValue be the result of calling the ImplicitThisValue concrete method of GetBase(ref).
8. Return the result of calling the [[Call]] internal method on func, providing thisValue as the this value and
providing the list argList as the argument values