Is there any value when passing a global variable to a function?

I recently saw code that looks like this:

(function (someGlobal) { someGlobal.DoSomething(); })(someGlobal); 

where someGlobal was a large wireframe class. It could be jQuery. What is the use of this? Is this a good practice? It looks like this code will be equivalent and less error prone because you are not hiding the global:

 (function () { someGlobal.DoSomething(); })(); 
+4
source share
4 answers
  • Do you have a reliable link if global is rewritten

  • It shortens the scope chain for access to it


"It seems that this code will be equivalent and less error prone because you are not hiding the global:"

 (function () { someGlobal.DoSomething(); })(); 

If you expect the global file to be overwritten and your code to use the rewritten value, then obviously you will not want to obscure its local variable in the function.

In addition, the local link in the function should no longer be error prone.

+2
source

I agree, if this is a global variable, then why transmit it? Just use it as a global one.

However, it looks like this may be a valid transition mechanism to remove the global one. For example, if I inherited a large code base with a large number of global variables, one of the possible transition mechanisms would be to slowly eliminate global customs in this way. This change could be made gradually with minimal differences.

+1
source

The advantage is that within this function someGlobal unambiguous.

0
source

This way you can use an alias in a safe area.

 (function ($) { $.DoSomething(); })(someGlobal); 

Update:

The most important thing related to this has identified a safe area for using someGlobal .

If you use the second method, someGlobal is still global, just the image you use someGlobal in the callback function, and you rewrite someGlobal somewhere outside, what will happen?

0
source

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


All Articles