Why do we localize global libraries / links?

Additionally, variables can be passed to an anonymous wrapper to localize publicly accessible global variables such as window, document and jQuery ...

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

What is the point of this localization if they are available all over the world?

+5
source share
4 answers

Passing variables to the module to localize them will give a faster search time, if I'm not mistaken, because they are in the local area.

In addition, it ensures that $ indeed a jQuery library. It protects $ from corruption by other uses.

+2
source

I would say that it provides a slightly faster search, because it is in the local area, but also reduces the file size when it is mined. The "parmers" window and the "document" can be minimized, but not global variables.

$ is often overwritten by other libraries (prototype), so it provides $ point for real jQuery passed in the parameter.

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

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

+4
source

In addition to improving minifraction and preventing name collisions, local variables can be viewed much faster:

enter image description here

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

+2
source

Global variables are known anti-pattern . Localizing global variables minimizes the disadvantages of using global variables.

It is also associated with DI . For example: what if you have 10 modules and you want one of them to use a replacement for jQuery, for example. zeptojs . If all your modules used global jQuery or $, you could not do this.

It is also useful to explicitly identify your dependencies, which is achieved using this localization technique. It increases readability and reduces grip.

+1
source

Source: https://habr.com/ru/post/1201117/


All Articles