Cover

JavaScript for the C# Guy: The Global Object

This is another in my series about (hopefully) interesting JavaScript constructs that might surprise most C# developers. You can see others here: JavaScript for the C# Guy.

Back in the day I was doing some scripting in classic ASP sites (no, not classic ASP.NET) and we screamed and yelled about putting too much in the global scope. We wanted encapsulation and such and that is true today. In my C# work pretty much everything is in a class (static or otherwise) so I don’t have to concern myself with it much.  But in JavaScript I know there is an easily accessible global object…but it occurred to me that I don’t see the “Global” object accessed much; even though it is used a bit (to hold other containers that have encapsulated code). “Why not?” I wondered.

In JavaScript you can certainly create things in the global space. In fact, in my Architecting JavaScript post from my Modern Web Development series, I show that using an ‘app’ object for your site can simplify a lot of things. But the app object needs to be in the global space (e.g. in the “Global” object) so everyone can get to it:

// app.js
(function (a, $) {
 
  a.setStatusMessage = function (message) {
    $('#status-message').text(message);
  };
 
} (window.app = window.app || {}, jQuery));

This code is creating a function that passes in a global object called ‘app’. This ‘app’ object is going to be a singleton that all scripts can add to so it is a canonical example of use of a global object since lots of code will interact with it. Great…but…in this case the code doesn’t put the object in the global scope, but attaches it to ‘window’ object.

What does that imply? While reading up on it in the great book “Professional JavaScript for Web Developers”, I found the answer. It seems that the JavaScript language supports a global object, but the spec that the web browsers use (ECMA-262) doesn’t tell them how to allow access to the ‘Global’ object. It seems that the web browsers implement this by making "window’ implement the access to the Global object. This means anything in the global space is accessible on the ‘window’ object. (The “window” object has a bunch of other responsibilities too, not just a alias for the Global object).

While this is true in our example, it also means that objects created in the global scope are also on window. For example:

// Some.js
var name = "foo";

function whatIsFoo() {
  return name;
}

var result = window.whatIsFoo(); // works

In this example both ‘whatIsFoo’ and ‘name’ are both accessible from the window property. Makes sense (though an odd place for it IMO).

Have you run into this peculiarity?