Stoyan Stefanov says in JavasScript Patterns that: "you need an immediated function to wrap all your code in its local scope and not to leak any variables to the global scope" page 70.
Here is his example
(function() {
var days = ['Sun','Mon'];
// ...
// ...
alert(msg);
}());
But surely because days is defined as a var, it will just be functional scope? The only benefit of the immediate function is the function is invoked immediately. There is no scope advantage. Corrcet?
It's not about an immediately executed function vs. a regular function; in fact it has very little to nothing in relation.
The sole purpose of an immediately invoked wrapping-function is to scope variables local to the wrapping function.
(function() {
// This variable is only available within this function's scope
var thisIsTemp = "a";
// ...
}());
console.log(thisIsTemp); // undefined
vs:
// This variable is available globally
var thisIsTemp = "a";
// ...
console.log(thisIsTemp); // "a"
Having your days
variable in the function scope is exactly the point that example is making. Without the immediately-invoked function, all the variables (days
, msg
) would be global variables, and will pollute the global namespace.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With