问题
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() { ...
回答1:
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.
来源:https://stackoverflow.com/questions/13759682/what-is-the-benefit-of-assigning-a-self-executing-anonymous-function-to-a-variab