Hello JS experts!
I'm reading some posts about closures and see this stuff all over the places, but there is no explanation how does it works - just every time I'm told to use it...:
// Create a new anonymous function, to use as a wrapper
(function(){
// The variable that would, normally, be global
var msg = "Thanks for visiting!";
// Binding a new function to a global object
window.onunload = function(){
// Which uses the 'hidden' variable
alert( msg );
};
// Close off the anonymous function and execute it
})();
Ok I see that we will create new anonymous function and then execute it. So after that this simple code should work (and it does):
(function (msg){alert(msg)})('SO');
My question is what kind of magic come to place here? I thought that when I wrote:
(function (msg){alert(msg)})
then new unnamed function will be created like function ""(msg) ...
but then why this does not work?
(function (msg){alert(msg)});
('SO');
Why it need to be in the same line?
Could please point me the the some post or give me the explanation?