将自执行匿名函数分配给 javascript 中的变量有什么好处? [英] What is the benefit of assigning a self executing anonymous function to a variable in javascript?
问题描述
我正在阅读帖子关于如何在完成窗口大小调整后触发函数,并遇到了一些将自执行匿名函数分配给变量的示例:
var delay = (function(){无功计时器= 0;返回函数(回调,毫秒){clearTimeout(定时器);定时器 = 设置超时(回调,毫秒);};})();$(window).resize(function() {延迟(功能(){alert('调整大小...');//...}, 500);});
与传统用途相比,使函数操作数自执行有什么区别/好处?即
var delay = function() { ...
造成这种情况的主要原因是命名空间变量.函数引入了一个新的变量作用域.在上面的例子中,timer
不会破坏全局命名空间,同时仍然可供需要它的代码使用.
因为我显然需要澄清:
目标是在函数外有一个变量:
var 定时器;函数延迟(){//使用定时器}
因为如果变量在函数内部,它每次都会被重新初始化.不过,我们希望在函数之外有一个持久值.
在上面的代码中 timer
是一个全局变量.我们不想要那样.为了避免这种情况,我们将变量关闭在一个新的作用域中,以便 delay
函数可以访问它,但不能全局访问:
var delay = (function() {无功定时器;返回函数(){//使用定时器};})();
delay
现在是一个和以前一样的函数,它可以在自身之外使用 timer
,但 timer
不在全局范围内.>
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() { ...
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.
Since I apparently need to clarify:
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.
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
is now a function just as before which can use timer
outside itself, yet timer
is not in the global scope.
这篇关于将自执行匿名函数分配给 javascript 中的变量有什么好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!