I was reading through the javascript design patterns book and came across the code below, while reading “The Command Pattern”. I’ve been trying to understand why this code is wrapped around an anonymous function which is immediately invoked, especially since there is no other private variables to be closured with. How is this different from just declaring CarManager as an object literal?
(function(){
var CarManager = {
// request information
requestInfo: function( model, id ){
return 'The information for ' + model + ' with ID ' + id + ' is foobar';
},
// purchase the car
buyVehicle: function( model, id ){
return 'You have successfully purchased Item ' + id + ', a ' + model;
},
// arrange a viewing
arrangeViewing: function( model, id ){
return 'You have successfully booked a viewing of ' + model + ' ( ' + id + ' ) ';
}
};
})();
The example is slightly half-baked.
The goal is to be able to provide a public-interface.
Inside of that IIFE, you put together all of the pieces required for your interface.
You don’t have to pass it back out through a return statement.
jQuery, for example, is built in the same way.
Instead of having a return statement:
They manually set
window‘sjQuery(and$) properties from within the function, like so:Moreover, what’s actually happening is a little bit different, still.
They’re passing the
windowobject into the IIFE’swindowparameter.It doesn’t have to be
window, then.It could be any previously-defined object you’re extending, in theory.
When building libraries similar to jQuery, you can do similar.
If you typically namespace any large libraries/applications (a good idea), you can shorten the name, internally, to make life easier.
Instead of:
var NAMESPACED_AWESOME_APP_OF_DOOM = {};
NAMESPACED_AWESOME_APP_OF_DOOM.module1 = {};
You can do something like:
Then you can do all of your internal setup inside, and once your setup is complete, you can reference the application by name, in the global scope.
In other cases, you can create sandboxes for code, using closures in this way, with mediators to send messages back and forth between components.
Nicholas Zakas has a couple of good talks on this.
And lastly, sometimes you just want some work to get done, which is 100% irrelevant to the rest of your program, but still needs to get done, all the same (like doing compatibility-checks and tying the results to the DOM elements, a la Modernizr… …or setting cookies that just need to be there, or firing off calls to analytics software… …et cetera).