Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we localize global libraries/references? [duplicate]

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?

like image 994
Nik Terentyev Avatar asked Aug 26 '14 03:08

Nik Terentyev


1 Answers

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

like image 177
bokan Avatar answered Oct 19 '22 23:10

bokan