10

We see this approach used all the time:

(function (window) {
    var document = window.document,
        location = window.location,
        navigator = window.navigator;
})(window)

When studying above snippet I wonder why a globally accessible object like window is passed as an argument to a function. Could it be that:

  1. The developer can not with 100% certainty know that window is accessible from within the local function scope?
  2. Is is good practice because you make your intentions clear to other developers that read your code.
  3. You've seen John Resig do it so it must be finger lickin' good!

What do you think?

Ray Toal
  • 79,229
  • 13
  • 156
  • 215
ChrisRich
  • 6,698
  • 9
  • 37
  • 56

3 Answers3

4

It makes the code more portable.

You can copy and paste the code to an environment that does not have global window object defined (e.g. node), but is API compatible for all the things you care about within your code. Then you only have to modify the argument passed to the function.

A slight modification that makes the code clearer:

(function(root){
    var document = root.document,
        location = root.location,
        navigator = root.navigator;
})(window)
Ray Toal
  • 79,229
  • 13
  • 156
  • 215
Matt York
  • 15,261
  • 5
  • 43
  • 50
2

I know of a couple possible reasons for the the code you asked about:

  1. Creating shortcuts for document, location and navigator in local variables is potentially a slight performance improvement and is a reduction in typing.

  2. Passing window into the self executing function might cause references to window to perform slightly better than using it from the global space.

  3. There are some execution environments for javascript (not in a browser) where the global object is not called window so the code could be more easily adapted to that. But, this reason seems like a bit of a stretch to be viable because code written for a browser is highly likely to use other browser capabilities anyway.

jfriend00
  • 580,699
  • 78
  • 809
  • 825
0
(function ($) { }(jQuery)); // $ stands for jQuery within this function
(function (window) { }(window)); // window still equals window
(function (bananas) { }(document)); // all references to bananas => document. (silly)
  1. Typically the top name is what you want it to be named, while the bottom insures what it is supposed to represent. So having $ in the top means that all of your jQuery code (in this instance) remains with jQuery. Using it for window/window just ensures that no other definition of window changes its original intent as 'window'.
  2. It is definitely a best practice, and controlled way of allowing what you want inside of your anonymous function/namespace.
  3. One of the reasons! Resig is the man.
Mark Pieszak - Trilon.io
  • 44,537
  • 13
  • 74
  • 89