Short answer
In the expression
obj.f()
this
within f
will be bound to the value of obj
(the expression on the left hand-side of the .
).
If a function is invoked "alone", i.e.
f()
then this
within f
is bound to the global object (in the browser, window).
That said, you can set the context before hand using the .bind
function, i.e.
var g = obj.f.bind(obj);
f(); // success! this == obj
c.f. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
You might also want to take a look at the .call
and .apply
functions.
Key point: functions DO NOT carry a context around. obj.f
is a member access, all it does is return the value of the property f
from obj
. The context is set when you CALL the function, either with obj.f()
or f()
in f
exists in the global scope, in which case the context would be the global object.
Long answer
Read the specs! :) http://www.ecma-international.org/ecma-262/5.1/#sec-10.3