jQuery: sandbox, namespaces, OOP for better applications

jQuery: sandbox, namespaces, OOP for better applications

How to safely run our jQuery applications without polluting the global namespace.

All properly coded jQuery applications should have their own namespace and live within the global jQuery namespace. To accomplish this, we have to use some coding practices borrowed from plugin development combined with the most advanced OOP techniques offered by jQuery. Let's see the details.

Creating a sandbox

First we need to create a sandbox where our code can safely run without polluting the global namespace:

(function($) {

   // App here
   
   $(function() {
   
   		// initialize the app
   
   });

})(jQuery);

Now all our jQuery code lives within our sandbox so that any possible conflict is practically avoided.

Using OOP techniques

Here's how we'll define our application:

(function($) {
    
    var App = {};
    
    $.extend(App, {
        version: '1.0',
        init: function() {
            alert(this.version);
        }
    }
   );
    
    $(function() {
        
        App.init();
        
    });
    
})(jQuery);​

We're using the jQuery's $.extend() utility method to add properties and methods to our application. This is the most flexible way current available in jQuery. You can see the demo below.

Demo

Live demo