简体   繁体   English

将全局变量传递给函数是否有价值?

[英]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. someGlobal是一个大型框架类。 It could be JQuery. 它可能是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 . 最重要的是这种方式为您定义了使用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? 如果你使用第二种方式, someGlobal仍然是一个全局的,只是你在回调函数中使用someGlobal ,并且你在外面某处覆盖someGlobal ,会发生什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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