Possible Duplicate:
JavaScript: Why the anonymous function wrapper?
I would like to ask you what is the reason of wrapping everything in
(function() {
document.write("Hello World!");
})();
function?
the initialize function is called everytime when the script is instantiated so any code within the function is executed no matter the sub-function that is called via the external script. This is useful for declaring re-usable variables, starting logging etc.
the Init Functions in JavaScript. When functions are used only once, an Immediately Invoked Function Expression (IIFE) is common. Copy (function() { /* Set of instructions */ })(); (() => { /* Set of instructions */ })(); IIFEs are function expressions called as soon as the function is declared.
functions are data in memory stack, so when you define another function with the same name, it overrides the previous one. Show activity on this post. Well obviously you're not meant to define the same function twice. However, when you do, the latter definition is the only 1 that applies.
Self executing anonymous function's main purpose is to wrap everything in a private namespace, meaning any variables declared do not pollute the global namespace, basically like a sandbox.
var test = 1;
test
would pollute the global namespace, window.test would be set.
(function() {
var test = 1; alert( test );
})();
window.test is undefined, because it's in our private sandbox.
That "protects" the global namespace from contamination.
(function() {
var something = "a thing";
// ...
if (something != "a thing") alert("help!");
// ...
function utility(a, b) {
// ...
};
// ...
})();
Now, those temporary variables and functions are all protected inside that outer throw-away function. Code inside there can use them, but the global namespace is kept clean and free of dirty, unwanted variables.
The global namespace is a precious resource. We should all be aware of its importance to ourselves and, especially, for our children.
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