为什么要将全局变量传递给函数?
Why would you pass a global variable to a function?
我见过用两种方式编写的相同代码,想知道它们之间是否存在任何折衷。
方法一:
(function(i) {
// Do something to i now
}(global_variable))
方法二:
(function() {
// Do something to global_variable now
}())
如果全局变量无论如何都会存在于该作用域中,为什么要将它传递给函数?
在这种情况下,它明确说明此函数使用全局变量并创建更易于键入的别名。此外,它使访问变量的速度更快一些,因为它不需要搜索所有范围,直到在全局范围内找到它。
对于常规函数,而不是您示例中的 iife,它使您的函数更易于测试,因为您可以更轻松地模拟传入的全局变量。
用于别名,例如:
(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;
//...
})()
或包含一个值,如本示例:
(function($){
//in here, $ preserves the passed/injected value,
//even if the global value changes
})(jQuery.noConflict())
这样您甚至可以在同一页面中使用多个版本的 jQuery。
当您出于某种原因不想永久更改 global_variable
的值时,您可能希望使用第一个示例。例如。执行此代码后,本地副本将被更改,但全局变量将保持不变。
global_variable=true; (function(i){ i=false; return i; }(global_variable));
然而,这段代码显然改变了 global_variable
:
global_variable=true; (function(){ global_variable=false; }());
编辑:有点切线,这个变体看起来像是改变了全局变量,但实际上并没有,因为调用函数会创建全局变量的影子副本。您可能应该避免这种模式,因为它可能会造成混淆:
g=true; (function(g){ g=false; return g; }(g));
我见过用两种方式编写的相同代码,想知道它们之间是否存在任何折衷。
方法一:
(function(i) {
// Do something to i now
}(global_variable))
方法二:
(function() {
// Do something to global_variable now
}())
如果全局变量无论如何都会存在于该作用域中,为什么要将它传递给函数?
在这种情况下,它明确说明此函数使用全局变量并创建更易于键入的别名。此外,它使访问变量的速度更快一些,因为它不需要搜索所有范围,直到在全局范围内找到它。
对于常规函数,而不是您示例中的 iife,它使您的函数更易于测试,因为您可以更轻松地模拟传入的全局变量。
用于别名,例如:
(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;
//...
})()
或包含一个值,如本示例:
(function($){
//in here, $ preserves the passed/injected value,
//even if the global value changes
})(jQuery.noConflict())
这样您甚至可以在同一页面中使用多个版本的 jQuery。
当您出于某种原因不想永久更改 global_variable
的值时,您可能希望使用第一个示例。例如。执行此代码后,本地副本将被更改,但全局变量将保持不变。
global_variable=true; (function(i){ i=false; return i; }(global_variable));
然而,这段代码显然改变了 global_variable
:
global_variable=true; (function(){ global_variable=false; }());
编辑:有点切线,这个变体看起来像是改变了全局变量,但实际上并没有,因为调用函数会创建全局变量的影子副本。您可能应该避免这种模式,因为它可能会造成混淆:
g=true; (function(g){ g=false; return g; }(g));