So to get the ball rolling… I’ve recently discovered that (in a browser host) the pre-defined window object and the unnamed global object are the same thing:
alert(this === window); // alerts: true
So global context code that sets values on this is at the same time setting the same value on the window object:
this.x = 1024; alert(window.x); // alerts: 1024 alert(x); // alerts: 1024
As you can see in the above example, in addition to this (the global object) and window being the same thing, unqualified top-level variables are also scoped in the global object.
Another point to be made here is that window is actually a property on the global object that references the global object itself. Consider the following:
x = 1024; alert(window.x); // alerts: 1024 alert(this.x); // alerts: 1024 alert(this.window.window.window.window.x); // alerts: 1024
So I thought I was understanding all of this until I attempted the following:
alert(this.window === window); // alerts: false in IE
I felt certain these would be the exact same object reference, but apparently not. Along the same lines I currently am not understanding the different behavior in these lines of code:
this.x; // no error window.x; // no error x; // ReferenceError: x is not defined
What is the difference between this.x being undefined (no error) and unqualified x being undefined? I plan to investigate and hopefully follow-up with a better explanation in a future posting. Any ideas out there?
undefined, attempting to access an undeclared global variable generates an error.
Edit 6/20/11: I think a more accurate explanation for the behavior of
this.x; is that when specifying the
window or global (this) object we are terminating the identifier resolution process. Without the qualification the identifier resolution process continues until the scope chain is exhausted.