Before any JavaScript is executed, the browser creates a formal default object in which all client-side code is contained. This object is known by many names which include: window object, head object, and global object. This might be news to you, it might not be. More importantly, conceptually, this means that by default the browser creates this object for us. You might not be aware of this if you have only ever written programs in the global scope using the var keyword and named functions. Well, its time for a look behind the curtain.
Because the window object is the global object, all JavaScript written for browser parsing will be placed inside of the global object as properties. For example, when you use the keyword var in the global scope its really just a short cut for adding a property to the window object. For example, consider the following statement:
var AAA = null;
behind the scenes it's really doing this:
window.AAA = null;
Additionally, named functions, just like the prior example are simply added to the global object as a property. Here is an example of a named function that behind the scenes is being added to the global object as a property. (When an objects property contains a function its often called a method.)
function BBB() { return; }
Behind the scenes its really doing this:
window.BBB = function() { return; };
Now let us verify what I am saying is true. Have a look at all the properties of the window object and make sure we see our custom properties included among the default properties.
If you run the html page in a browser you should see the custom properties AAA and BBB in the list of properties for the window object. The truth is, when using var and named functions in the context of the global scope, you are really just adding properties to the window object. Just for fun, I've created a function (code below) that will list out all the properties for the window object, and several of the objects contained inside of the window object that pertain to the DOM. See anything interesting about our AAA and BBB properties? If not, make sure to checkout the frames object.
Wait, before you go I also want to mention that knowing what is in the global scope is pretty handy. Open any web page you like in Firefox, and from the Firebug command line, run the follow code:
This will add to the bottom of the HTML page a list of all the properties contained within the global window object.