I'm a moderately skilled programmer using JavaScript but I am no guru. I know you can do some pretty powerful things with it, I just haven't seen much other than fairly basic DOM manipulation. I'm wondering if people could provide some examples of traditional design pattern concepts such as Factory Method, Singleton, etc using JavaScript. In what cases would these patterns be used for on the web?
I just wanted to add my favorite JavaScript pattern that I learned from Pro JavaScript Design Patterns which Jonathan Rauch already recommended.
It is the namespace singleton pattern. Basically, you create namespaces via singletons which allow you to hide methods and variables from external use. The hidden/exposed methods are actually hidden because they are defined within the closure.
var com = window.com || {};
com.mynamespace = com.mynamespace || {};
com.mynamespace.newpackage = (function() {
var myPrivateVariable = "hidden";
var myPublicVariable = "exposed";
function myPrivateMethod() {
return "also hidden";
}
function myPublicMethod() {
return "also exposed";
}
return {
myPublicMethod: myPublicMethod,
myPublicVariable: myPublicVariable
};
})();