简体   繁体   English

为什么要将全局变量传递给函数?

[英]Why would you pass a global variable to a function?

I've seen the same code written both ways and wonder if there's any tradeoff between them. 我已经看到了两种方式编写相同的代码,并想知道它们之间是否有任何权衡。

Method 1: 方法1:

(function(i) {
    // Do something to i now
}(global_variable))

Method 2: 方法2:

(function() {
    // Do something to global_variable now
}())

Why would you pass a global variable to a function if it's going to exist in that scope anyway? 如果它仍然存在于该范围内,为什么要将全局变量传递给函数?

In this case, it gives clear instructions that this function uses a global and creates an easier to type alias. 在这种情况下,它给出了明确的说明,即此函数使用全局并创建更容易键入的别名。 Also, it makes accessing the variable a little faster because it doesn't need to search all the scopes until it finds it in the global scope. 此外,它使访问变量的速度更快,因为它不需要搜索所有范围,直到它在全局范围内找到它。

In the case of regular functions, not an iife as in your example, it makes your function more testable because you can mock the global that is passed in more easily. 对于常规函数,而不是示例中的iife,它会使您的函数更易于测试,因为您可以更轻松地模拟传递的全局函数。

for aliasing purposes for example: 出于别名的目的,例如:

(function(leeloo){

    //inside here you can use the short term

})(LeeloominaiLekataribaLaminaTchaiEkbatDeSebat)

//this would be similar, it's a matter of preference
(function(){
    var leeloo = LeeloominaiLekataribaLaminaTchaiEkbatDeSebat;

    //...
})()

or to enclose a value, like this example: 或者包含一个值,如下例所示:

(function($){

    //in here, $ preserves the passed/injected value, 
    //even if the global value changes

})(jQuery.noConflict())

this way you could even use multiple versions of jQuery in the same page. 这样你甚至可以在同一页面中使用多个版本的jQuery。

You might want to use the first example when you don't want to permanently change the value of global_variable , for some reason. 出于某种原因,当您不想永久更改global_variable的值时,可能需要使用第一个示例。 Eg after executing this code the local copy will be changed but the global variable will be unchanged. 例如,执行此代码后,本地副本将被更改,但全局变量将保持不变。

global_variable=true; (function(i){ i=false; return i; }(global_variable));

This code however, obviously alters global_variable : 但是,这段代码显然会改变global_variable

global_variable=true; (function(){ global_variable=false; }());

Edit: somewhat tangentially, this variation looks like it alters the global variable, but it doesn't because calling the function creates a shadow copy of the global variable. 编辑:有点切线,这种变化看起来像是改变了全局变量,但它没有,因为调用函数会创建全局变量的卷影副本。 You should probably avoid this pattern since it's likely to create confusion: 您应该避免使用此模式,因为它可能会造成混淆:

g=true; (function(g){ g=false; return g; }(g));

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

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