Essential JavaScript Design Patterns For Beginners by Addy Osmani is a minibook published online.
Let me quote ‘Revealing Module Pattern’ code snippet which I find very neat.
/* The idea here is that you have private methods which you want to expose as public methods. What are are doing below is effectively defining a self-executing function and immediately returning the object. */ var myRevealingModule = (function(){ var name = 'John Smith'; var age = 40; function updatePerson(){ name = 'John Smith Updated'; } function setPerson () { name = 'John Smith Set'; } function getPerson () { return name; } return { set: setPerson, get: getPerson } }()); // Sample usage: myRevealingModule.get();
Compare it with module pattern.
var myNamespace = (function(){ var myPrivateVar = 0; var myPrivateMethod = function(someText){ console.log(someText); } return { myPublicVar: "foo", myPublicFunction: function(bar){ myPrivateVar++; myPrivateMethod(bar); } } })();
I really enjoyed reading it. In addition to the design pattern article, you may like to read my articles on some javascript patterns:
– Inheritance and Objects in Javascript
– Inheritance, Closure, Module practice in Javascript
– Functions in Javascript
This article follows Attribution-NonCommercial-ShareAlike 3.0 license.