iife - What is the (function() { } )() construct in JavaScript? -
i used know meant, i'm struggling now...
is saying document.onload
?
(function () { })();
it’s immediately-invoked function expression, or iife short. executes after it’s created.
it has nothing event-handler events (such document.onload
).
first pair of parentheses (function(){...})
turns code within (in case, function) expression, , second pair of parentheses (function(){...})()
calls function results evaluated expression.
this pattern used when trying avoid polluting global namespace, because variables used inside iife (like in other normal function) not visible outside scope.
why, maybe, confused construction event-handler window.onload
, because it’s used this:
(function(){ // code here var foo = function() {}; window.onload = foo; // ... })(); // foo unreachable here (it’s undefined)
correction suggested guffa:
the function executed right after it's created, not after parsed. entire script block parsed before code in executed. also, parsing code doesn't automatically mean it's executed, if example iife inside function won't executed until function called.
Comments
Post a Comment