I know that top-level functions are members of the window object, and it’s consistent with the fact that this inside them refers to the window.
But for non-top level functions, this is still window, but they are not members of window!
Here’s some code:
function topLevel1() {
alert(this)
}
function topLevel2() {
function inner() {
alert(this)
}
inner()
}
topLevel1() // alerts DOMWindow
alert(window.topLevel1) // alerts text of topLevel1, as expected
topLevel2() // again, alerts DOMWindow
alert(window.inner) // undefined
alert(window.topLevel2.inner) // undefined
- If
inneris neither a member ofwindownor oftopLevel2, whose member is it? - How can it be that it’s
thisiswindow, but it’s not awindow‘s member? - Isn’t it a law in Javascript that if
this == owner, then the current method was called viaowner.? (except special cases like constructors,apply,call, etc)
Again, the
thisvalue of a function is decided of how the function is invoked, not where it is located or how it was designed.If you just call a function
anywhere in your code, just like that, its
thisvalue will always bewindow(non-strict mode) orundefined(strict). Now there are plenty of ways to modify thethis, like calling the function with.apply(),.call()or.bind(). All of those methods give your the opportunity to modify thethisvalue for a given function. Also, if you call a function with thenewkeyword,thisreferes to a newly created object (which is also returned).So, location of a function tells you zero about its context or
this.Now to answer your specific questions:
inneris a member of theActivation ObjectfromtopLevel2(ES3)described above
I guess thats also covered above