“The this keyword always refers to the object that the containing function is a method of.”
Great, sounds simple enough, but here’s what I’m wondering about…
For example:
function func1() {
function func2() {
alert(this == window); // true
}
func2();
alert(this == window); // true
}
func1.func3 = function () {
alert(this == window); // false
alert(this == func1); // true
};
func1();
func1.func3();
Now, since func1 is actually a method of the global (window) object (a function object assigned to the property func1 of the global object) it makes sense that this inside func1 refers to the global object, and since func3 is a method of func1‘s function object it makes sense that this inside func3 refers to func1‘s function object.
The thing that bothers me is func2. I know that this inside a nested function is also supposed to reference the global object, but I’m not sure why since func2 is NOT a method of the global object. As far as I understand (and this is the part I might be completely wrong about) func2 is a method of func1‘s call (activation / variable) object. Now, if I’m right about this (and I’m not sure that I am) then shouldn’t this inside func2 refer to func1‘s call object instead of the global object?
So, I guess my question would be: Is a nested function a method of the call (activation) object of the function it is nested in, and if so, shouldn’t this refer to that call object instead the global object?
No. Unfortunately, it is not easy as that. The documentation of the
thiskeyword at MDN gives a good overview. It is set to the object when the function is called as a method on it, but there are other possibilies. The default is thatthisisundefinedwhen it is called without anything special, like you do withfunc1andfunc2. For sloppy (non-strict) mode functionsundefined(andnull) are not used though,thisdoes point to the global object (windowin browsers) for them in that case – what you are observing.But it could also point to fresh object instances when the function is called as a constructor (with the
newkeyword), or to an event target (like a DOM element) when used as a handler. Last, but not least, it could be set manually withcall,applyorbind…thishas nothing to do with nesting. Nesting function declarations/expressions only affects the scope (“privacy”, availability) of variables. While the variable scope of a function never changes, the value ofthiscan be different on every invocation – it is more like an extra argument.