Calling a function as part of an expression where you get the function reference from an object property calls the function with this
set to the object you got the property from.
So your code:
s.test1();
...will call test1
setting this
equal to the object referenced by s
, because the call is part of an expression getting the test1
function reference from a property on the object s
refers to.
Then in test1
, when you do:
this.test2();
...it calls test2
setting this
equal to the object referenced by this
, because the call is part of an expression getting the test2
function reference from a property on the object this
refers to.
Where you'd run into a problem with this
not being set correctly would be if you didn't call test1
or test2
via an object property, like this:
var f = s.test1;
f();
Then, within the call to test1
, this
would be the global object (in loose mode) or undefined
(in strict mode). The same sort of thing happens when passing a function as an argument:
foo(s.test1);
If foo
calls the function its first argument relates to, we get the same thing (this
= global object or undefined
).
Since you're not doing that, though, that doesn't happen.
The key thing here is how the function is called, not where it's defined (inside another function or not).
More on this
in How Does The this
Keyword Work? here on SO, and in Mythical methods and You must remember this
on my blog.