将自动执行的匿名函数分配给javascript中的变量有什么好处? [英] What is the benefit of assigning a self executing anonymous function to a variable in javascript?
问题描述
我正在阅读帖子关于在窗口调整大小后如何触发函数的信息,并遇到了一些将自执行匿名函数分配给变量的示例:
I was reading a post about how to fire a function after a window resize was complete and came across some examples that assigned self executing anonymous functions to variables:
var delay = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
$(window).resize(function() {
delay(function(){
alert('Resize...');
//...
}, 500);
});
使函数操作数自动执行与传统用法相比有什么区别/好处?即
What is the difference/benefit of making the function operand self executing as opposed to it's traditional use? i.e.
var delay = function() { ...
推荐答案
主要原因是命名空间变量.函数引入了新的变量范围.在上面的示例中,timer
不会破坏全局名称空间,同时仍可用于需要它的代码.
The main reason for this is namespacing variables. Functions introduce a new variable scope. In the case of the above example, timer
is not clobbering the global namespace while still being available to the code that needs it.
由于我显然需要澄清:
目标是在函数外部具有一个变量:
The goal is to have a variable outside the function:
var timer;
function delay() {
// use timer
}
由于该变量位于函数内部,因此每次都会将其重新初始化.但是,我们希望在函数外提供一个持久值.
Because if the variable would be inside the function, it would be reinitialized every time. We want a persistent value outside the function though.
在上面的代码中,timer
是一个全局变量.我们不想那个.为避免这种情况,我们将变量封闭在新的范围内,以便delay
函数可以访问它,但不能全局访问:
In the above code timer
is a global variable though. We don't want that. To avoid that, we close the variable up in a new scope so it's accessible to the delay
function, but not globally:
var delay = (function () {
var timer;
return function () {
// use timer
};
})();
delay
现在就像以前一样可以在其外部使用timer
,但是timer
不在全局范围内.
delay
is now a function just as before which can use timer
outside itself, yet timer
is not in the global scope.
这篇关于将自动执行的匿名函数分配给javascript中的变量有什么好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!