When you invoke a top-level function in Javascript, the this keyword inside the function refers to the default object (window if in a browser). My understanding is that
Whether a function is nested inside another one has nothing to do with the value of this
when the function is called. The only things that matter are:
If the function is "found" by traversing a property on an object, then the value of this
will be a reference to that object:
someObject.prop( whatever );
It doesn't matter how the function was declared.
If you use call()
or apply()
to invoke a function, then the value of this
is taken from the first argument to whichever of those functions you use.
If you've created a bound wrapper for the function with bind()
, then the value of this
will be as requested when bind()
was called.
If you're calling a function as a constructor with new
, then this
will refer to the newly-created object instance.
Otherwise, this
is either a reference to the global context, or else it's undefined
(in "strict" mode or in an ES5-compliant runtime).
The "location" in the code where a function is defined does matter, of course, in that the scope includes whatever symbols it includes, and those are available to the function regardless of how a reference to it is obtained.