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?
Prototype Design Pattern in JavaScript The Prototype design pattern relies on the JavaScript prototypical inheritance. The prototype model is used mainly for creating objects in performance-intensive situations. The objects created are clones (shallow clones) of the original object that are passed around.
What is a Pattern? A pattern is a reusable solution that can be applied to commonly occurring problems in software design - in our case - in writing JavaScript web applications. Another way of looking at patterns are as templates for how we solve problems - ones which can be used in quite a few different situations.
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
};
})();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With