Looking at this David Fowler JS code , he transfers each “class” using an anonymous self-exploration method, where he sends in jQuery and window. I understand that this is a way to ensure that $ and windows are actually the jQuery and winndow global variables that you expect from them.
But isn't that too protective? If you protect yourself from someone else changing the $ variable and windows - is there really code that does this, and if so, why? Also, are there other benefits to packaging everything like this?
/ . , , Javascript , (, ) .
, - Javascript, , window.$ ( , , ), , jQuery.
window.$
- "a-hole". -
window.undefined = true;
...undefined . , / , .
undefined
(function(win, doc, $, undef) { }(window, window.document, jQuery));
, , jQuery, $.
, JavaScript- IIFE, , . , var.
var
- : , window " ", , minifier . , gzip, , .
window
IIFE , , , .js, . .
.js
,
(function () { var $ = jQuery; var window = window; // ... }());
- , .
Imaging that if every jQuery plugin is not wrapped in an anonymous function, then there will be hell global variables.
It is just to maintain integrity. $ may be Prototype, so sending jQuery as an argument will save your code if someone else adds a library / variable that overwrites $.
On the second argument to "window", I see it as the module you want to write.