5

Furthermore, variables can be passed into the anonymous wrapper to localize commonly accessed global variables, such as window, document, and jQuery...

var module = (function (window, document, $) {
    // module stuff
})(window, document, jQuery);

What is the point of this localisation if those are globally accessible anyway?

Nik Terentyev
  • 2,270
  • 3
  • 16
  • 23
  • 1
    this construction in use because of secure reason. Its very popular in JQ plugins. Imagine, you created plugin and have no info where it will be used, for e.g there is Prototype on page and if you will use `$` directly you will have bugs and errors for sure, thats why you provide Jquery as global object on page and $ as short form in params and be sure it Jquery – Evgeniy Aug 28 '14 at 08:09

4 Answers4

4

I would say that it ensure slightly faster lookup because it is in local scope, but also smaller file size when minified. The parmeters 'window' and 'document' can be minified, but not the global variables.

$ is often overwritten by other libraries (prototype) so this way it ensure $ point to the real jQuery passed in parameter.

Note that some also add the 'undefined' parameter since it is mutable in ECMAScript 3 (no longer in ES5).

See the comments of the jQuery boilerplate : https://github.com/jquery-boilerplate/jquery-boilerplate/blob/master/dist/jquery.boilerplate.js

bokan
  • 3,601
  • 2
  • 23
  • 38
2

Passing variables into a module to localize them will yield faster lookup times, if I am not mistaken, since they are in local scope.

In addition, it ensures that $ is indeed the jQuery library. It protects the $ from being tainted by another use.

therealrootuser
  • 10,215
  • 7
  • 31
  • 46
2

As well as providing better minifaction and avoiding name collisions, local variables are much faster to lookup:

enter image description here

http://jsperf.com/local-variable-scope

dave1010
  • 15,135
  • 7
  • 67
  • 64
1

Global variables are a known anti pattern. Localizing global variables minimizes the shortcumings of using global variables.

This is also related to DI. E.g.: what if you have 10 modules and you'd like one of them to use a replacement for jQuery, e.g. zeptojs. If all your modules used the global jQuery or $ you couldn't do that.

It's also good to expose your dependencies explicitly, which is achieved by this localization technique. It increases readbiltiy and reduces coupling.

Tom
  • 964
  • 9
  • 25