天天看點

two ways of IIFE(immediately-invoked-function-expression)-JS

one way:

file1, IIFE.js

(function() {
    var jQuery = {
        myAlert:function myAlert(){
            alert("IIFE Test");
        }
    };
    window.jQuery = jQuery;
})();
           

file 2,IIFE-test.html

<html>
    <script type="text/javascript" src="IIFE.js"></script>
    <script type="text/javascript">
        jQuery.myAlert();
    </script>
</html>
           

another way:

js codes,

var jQuery = function()
{
      var myAlert = function(){
           alert("test");    
      }
      return{
           myAlert : myAlert
      };
}();
           

omit html codes.

more:

1. http://learn.jquery.com/javascript-101/scope/

2. http://benalman.com/news/2010/11/immediately-invoked-function-expression/

繼續閱讀