javascript Module pattern
By Anatoly Mironov
Want organize your js code in a kind of namespaces, or modules, then use the module pattern. I’ll take the dummy example for getting the current anchor. Let’s look how it would be if the prototype based approach is used:
var Contoso.Utils = function() {};
Contoso.Utils.prototype = {
getCurrentAnchor: function() {
var url = window.location;
var anchor=url.hash; //anchor with the # character
var anchor2=url.hash.substring(1); //anchor without the # character
return anchor2;
}
};
var util = new Contoso.Utils();
var anchor = util.getCurrentAnchor();
```The [prototype pattern](http://weblogs.asp.net/dwahlin/archive/2011/08/01/techniques-strategies-and-patterns-for-structuring-javascript-code-the-prototype-pattern.aspx) reminds the classic object oriented programming. Now, how would it look in the module pattern:
var Contoso = Contoso || {}; Contoso.Utils = function() { //private var invokeCounter = 0; var logInvokeCounter = function() { invokeCounter++; console.log(“invoked: " + invokeCounter + " times”); } //public return { getCurrentAnchor: function() { var url = window.location; var anchor=url.hash; //anchor with the # character var anchor2=url.hash.substring(1); //anchor without the # character logInvokeCounter(); return anchor2; } } }(); var anchor = Contoso.Utils.getCurrentAnchor();
Type.registerNamespace(“Contoso”);