简体   繁体   中英

Is there value in 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 framework class. It could be JQuery. What is the benefit of doing this? Is it a good practice? It seems like this code would be equivalent and less error prone because you don't hide the global:

(function () {
    someGlobal.DoSomething();
})();
  • You have a reliable reference in case the global one gets overwritten

  • It shortens the scope chain to access it


"It seems like this code would be equivalent and less error prone because you don't hide the global: "

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

If you anticipate the global being overwritten, and your code relies on the overwritten value, then clearly you wouldn't want to shadow it by a local variable in a function.

Aside from that, the local reference in a function shouldn't be any more prone to error.

I agree if it's a global variable then why pass it? Just use it as a global.

However it does seem like this could be a valid transition mechanism to remove a global. For instance if I inheritted a large code base with a lot of globals, one potential transition mechanism would be to slowly eliminate the global usages in this exact manner. The change could be done this way incrementally with minimal diffs.

好处是,在该函数中, someGlobal是明确的。

This way you can use an alias name in a safe scope.

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

Update:

The most import thing is this way defined a safe scope for you to use someGlobal .

If you use the second way, the someGlobal is still an global, just imaging that you use someGlobal in an callback function, and you overwrite someGlobal somewhere outside, what will happen?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM