A Window and a Document walk into an Anonymous Closure

27 April 2011

Why use window and document and not aliases?

I pondered this the other day and I couldn’t really think of a reason not to. With an alias we can:

  • Redefine them as we would like; Useful for iframes and nodejs
  • File is smaller and minifies better
  • Less to type (probably not the strongest point)


I recently took to declaring these as constants at the top of each script.

(function () {
    var DOC = document,
        WIN = window;
    alert(DOC); //document
    alert(WIN); //window

Anonymous Closure Awesomeness

But how about a cleaner solution?

(function (DOC, WIN) {
    alert(DOC); //document
    alert(WIN); //window
}(document, window));

Awesomeness for YUI 2

When using YUI 2, I add the YAHOO object as the third argument

(function (DOC, WIN, Y) {
    alert(DOC); //document
    alert(WIN); //window
    alert(Y); //YAHOO object
}(document, window, YAHOO));

Awesomeness is already caked into YUI 3

When using YUI 3, none of the above is needed as the script is already sandboxed in the YUI().use method and the document and window are defined as Y.config.win and Y.config.doc.

    doc : document, //document by default (not required)
    win : window //window by default (not required)
}).use('node', function (Y) {
    alert(Y.config.doc); //document
    alert(Y.config.win); //window
    alert(Y); //YUI object

Matt Sain

Ramblings of a developer, designer and child subscribe

This blog is a public GitHub repository. If you find an error I will not be surprised... but if you fork and edit the blog and send me a pull request you'd be pretty awesome in my book.

Featured Repos