问题描述:

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.

网友答案:

The benefit is that, within that function, someGlobal is unambiguous.

网友答案:

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?

相关阅读:
Top