Why complete every prototype of a class object with an anonymous function in JS?

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?

+5
source share
5 answers

/ . , , Javascript , (, ) .

, - Javascript, , window.$ ( , , ), , jQuery.

- "a-hole". -

window.undefined = true;

...
undefined . , / , .

(function(win, doc, $, undef) {
}(window, window.document, jQuery));
+3

, , jQuery, $.

+5

, JavaScript- IIFE, , . , var.

- : , window " ", , minifier . , gzip, , .

IIFE , , , .js, . .

,

(function () {
    var $ = jQuery;
    var window = window;

    // ...
}());
+2

- , .

Imaging that if every jQuery plugin is not wrapped in an anonymous function, then there will be hell global variables.

0
source

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.

0
source

All Articles