Basic JavaScript Part 10: The Module Pattern
Here are the links to the previous installments:
- Functions
- Objects
- Prototypes
- Enforcing New on Constructor Functions
- Hoisting
- Automatic Semicolon Insertion
- Static Properties and Methods
- Namespaces
- Reusing Methods of Other Objects
- The module pattern is quite popular in the JavaScript community as is heavily applied by many JavaScript developers. There?s also the CommonJS initiative, which defines a specification for a common set of JavaScript API?s that are organized using self-contained modules. These specifications are supported by a growing community as they provide the foundation for the modules that are built into Node.js and numerous other open-source JavaScript libraries. This pattern has become so widespread because it?s an excellent way to package and organize an independent, self-containing piece of JavaScript code. The module pattern is composed by using self-executing functions combined with namespaces. Let?s show a simple example.
namespace('media'); media.podcast = (function(name) { var fileExtension = 'mp3'; function determineFileExtension() { console.log('File extension is of type ' + fileExtension); } return { download: function(episode) { console.log('Downloading ' + episode + ' of ' + name); determineFileExtension(); } } }('Astronomy podcast'));
First we define a namespace called media. Then we use a self-executing function that returns an anonymous object with a method named download that can be invoked by external code. Inside the self-executing function we have a variable fileExtension and a function determineFileExtension that are private and can only be used inside the module. Notice that we provide a fixed parameter value for the self-executing function. This technique is usually applied to pass in some kind of global object. jQuery uses this same approach to inject a reference to the global window object into the scope of its module.
- We can use the download method of our module like so ?
media.podcast.download('the first episode');
? which outputs what we expect:
Downloading the first episode of Astronomy podcast
File extension is of type mp3
The way we implemented the module pattern here has at least one major downside. We?re able to completely replace the implementation of the download method that is exported by the anonymous object returned from the self-executing function. This can become quite troublesome if we have other functions inside our module that also make use of the download method and thereby rely on its functionality. The way to fix this issue is to make all functions private and export them using the anonymous object:
namespace('media'); media.podcast = (function(name) { var fileExtension = 'mp3'; function determineFileExtension() { console.log('File extension is of type ' +fileExtension); } function download(episode) { console.log('Downloading ' + episode + ' of ' + name); determineFileExtension(); } return { download: download } }('Astronomy podcast'));
- The download method exposed by the anonymous object can still be replaced, but at least the correct implementation is preserved by the private download function for other functions that rely on its behavior. This approach is commonly called the ?revealing module pattern?.
- Another neat approach is to export a constructor function instead of an anonymous object.
namespace('media'); media.Podcast = (function() { var fileExtension = 'mp3'; function determineFileExtension() { console.log('File extension is of type ' +fileExtension); } var podcastConstructor = function Podcast(name) { if(false === (this instanceof Podcast)) { return new Podcast(); } this.getName = function() { return name; } } podcastConstructor.prototype.download = function (episode) { console.log('Downloading ' + episode + ' of ' + this.getName()); determineFileExtension(); } return podcastConstructor; }());
- Instead of returning an anonymous object from our self-executing function, we create another function and add the download method to the prototype of this constructor function. Notice that we also moved the name parameter to the constructor function instead of passing it into the self-executing function. At the end of the self-executing function we just return this constructor function like we did with the anonymous object.
- We can now use this module like so ?
var astronomyCast = new media.Podcast('Astronomy podcast'); astronomyCast.download('the first episode');
- ? which yields the same output as before.
- The module pattern is a very powerful concept in JavaScript. Being able to expose and use JavaScript code, treating it as a black box, is a very common technique that is used in lots of JavaScript libraries and frameworks.
Happy coding!
After reading this installment i just went through your previous posts within the series and was utterly impressed with your tutorials, i just want to tank you for bringing them to the people
Thanks for the kind words.
var podcastConstructor = function Podcast(name) {
if(false === (this instanceof Podcast)) {
return new Podcast();
}
FYI : IE 7 & 8 break on this. Error thrown :
Object doesn’t support this property or method
p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 8.5px Helvetica; color: #ff0000}
This technique is awsome but I have not seen it implemented in some Node.js libraries, for example socket.io.
I have seen the constructor/prototype standard technique using “_” for private members.
Do you know why?
Is for performance or to be able to access private members in TDD?
I’m not familiar with the socket.io codebase so I can’t give a conclusive answer to why they chose this pattern. It can be just a matter of preference as well.