vartestModule=(function(){varcounter=0;return{incrementCounter: function(){returncounter++;},resetCounter: function(){console.log("counter value prior to reset: "+counter);counter=0;},};})();// Usage:testModule.incrementCounter();testModule.resetCounter();
Singleton
varSingleton=(function(){varinstance;functioncreateInstance(){varobject=newObject("I am the instance");returnobject;}return{getInstance: function(){if(!instance){instance=createInstance();}returninstance;},};})();functionrun(){varinstance1=Singleton.getInstance();varinstance2=Singleton.getInstance();alert("Same instance? "+(instance1===instance2));}run();
Proxy pattern
functionGeoCoder(){this.getLatLng=function(address){if(address==="Amsterdam"){return"52.3700° N, 4.8900° E";}elseif(address==="London"){return"51.5171° N, 0.1062° W";}elseif(address==="Paris"){return"48.8742° N, 2.3470° E";}elseif(address==="Berlin"){return"52.5233° N, 13.4127° E";}else{return"";}};}functionGeoProxy(){vargeocoder=newGeoCoder();vargeocache={};return{getLatLng: function(address){if(!geocache[address]){geocache[address]=geocoder.getLatLng(address);}log.add(address+": "+geocache[address]);returngeocache[address];},getCount: function(){varcount=0;for(varcodeingeocache){count++;}returncount;},};}// log helpervarlog=(function(){varlog="";return{add: function(msg){log+=msg+"\n";},show: function(){console.log(log);log="";},};})();functionrun(){vargeo=newGeoProxy();// geolocation requestsgeo.getLatLng("Paris");geo.getLatLng("London");geo.getLatLng("London");geo.getLatLng("London");geo.getLatLng("London");geo.getLatLng("Amsterdam");geo.getLatLng("Amsterdam");geo.getLatLng("Amsterdam");geo.getLatLng("Amsterdam");geo.getLatLng("London");geo.getLatLng("London");log.add("\nCache size: "+geo.getCount());log.show();}run();