• Blogs (9)
    • πŸ“± 236 - 992 - 3846

      πŸ“§ jxjwilliam@gmail.com

    • Version: β€πŸš€ 1.1.0
  • JavaScript Namespace

    Blogs20142014-04-12


    JavaScript Namespace

    <script>
      (function($) {
        // Define functions, objects etc.
        var obj = {};
        var ary = [];
        function ConstractorFunction() {}
        ConstractorFunction.prototype = ...;
        var cf = new ConstractorFunction();
      	...
    
        // When Document is Ready:
        $(function() {
        }();
    
      }(jQuery));
    </script>

    It is better than without the ’(function(){})()’ scope, because it make the scripts is in a private scopes. If in a MVC structure, there are different JS files to be used, where Model, View, Controller need to share some global variables, the above ’(function(){})()’ will not work. Hoverver, by using namespace, this is very easy to solve, like this:

    //1. in model.js:
    <script>
    var app = app || {};
    (function() {
    	...
    })();
    </script>
    
    //2. in controller.js:
    <script>
    var app = app || {};
    (function() {
    	...
    })();
    </script>
    
    //3. in view.js:
    <script>
    var app = app || {};
    (function($) {
    	...
    })(jQuery);
    </script>
    
    // 4. Entry (probably in index.html):
    <script>
    var app = app || {};
    $(function($) {
    	// the global namespace 'app' is accessible
    	//app.model...
        //app.controller...
        //app.view...
    })(jQuery);
    </script>

    In this way, only ’app’ is exposed to global, and different js files can operate ’app’ in common. Very clean codes.