Why do you need to invoke an anonymous function on the same line?

前端 未结 19 1497
走了就别回头了
走了就别回头了 2020-11-22 00:17

I was reading some posts about closures and saw this everywhere, but there is no clear explanation how it works - everytime I was just told to use it...:

//          


        
19条回答
  •  醉话见心
    2020-11-22 00:58

    The IIFE simply compartmentalizes the function and hides the msg variable so as to not "pollute" the global namespace. In reality, just keep it simple and do like below unless you are building a billion dollar website.

    var msg = "later dude";
    window.onunload = function(msg){
      alert( msg );
    };
    

    You could namespace your msg property using a Revealing Module Pattern like:

    var myScript = (function() {
        var pub = {};
        //myscript.msg
        pub.msg = "later dude";
        window.onunload = function(msg) {
            alert(msg);
        };
        //API
        return pub;
    }());
    

提交回复
热议问题