Why does jQuery send in window to itself when it can just call it from within

91 views Asked by At

I tried this myself and I suppose its some sort of closure catch but I dont see the difference in this:

(function() {
 var tvLib = {}
 window.tvLib = tvLib
})();

from the jQuery way of :

(function(window, undefined) {
var jq;
window.jq = jq;
})(window);

Im confused why I need to send in window object if I can call it anyway.

2

There are 2 answers

0
Mattias Åslund On BEST ANSWER

One reason is to let minifiers rename the variable to make it more compact.

0
ngryman On

This is for minification / mangling purposes.

Mangling consists of renaming scoped variables to shorter names in order to gain some characters and obfuscate the code. For example, each occurrence of a scoped variable myVariable could be mangled to a in order to gain 9 characters each time it appears in the code.

window and undefined are both global variables, they cannot be mangled because it would obviously break the code. But if you assign scoped variable to their value / reference, those can be mangled. If your library (like jQuery) uses a lot window or undefined, this technique helps to reduce your code size further more.

So, taking your example:

(function(window, undefined) {
  var jq;
  window.jq = jq;
})(window);

Would give something like this mangled:

(function(a, b) {
  var c;
  a.c = c;
})(window);

On a side note, it's important to use the array-like syntax when you want to export global variables in order to avoid them to be mangled. So you can safely reference them externally.

This would be better in your example:

(function(window, undefined) {
  var jq;
  window['jq'] = jq;
})(window);

Would give something like this mangled:

(function(a, b) {
  var c;
  a['jq'] = c;
})(window);