JavaScript Singleton Design Pattern
The Singleton pattern restricts an instantiation of an object to a single instance thus reducing its memory allocation and allowing a "lazy loading" on an as-needed basis. The advantages of that pattern are the reduced memory occupation, single point of access and a postponed initialization which prevents instantiation until it is required. As a disadvantage one may point out that object is hardly ever reset once instantiated and sometimes there might be hidden dependencies.
<script type="text/javascript">
var singleton = ( function(window) {
function init() {
function action1() {
console.log("Action1");
}
function action2() {
console.log("Action2");
}
return {
action1 : action1,
action2 : action2
};
}
if(!window._instance) {
window._instance = new init();
}
return window._instance;
} )( window );
singleton.action1(); // action1 is called
singleton.action2(); // action2 is called
</script>
Another interesting singleton pattern implementation is the following:
<script type="text/javascript">
var Singleton = function() {
if (window._instance) {
return window._instance;
}
this.init();
window._instance = this;
};
Singleton.prototype = {
init: function() {
this.value = 5;
},
getValue: function() {
return this.value;
}
};
var singleton = new Singleton();
console.log(singleton.getValue());
</script>
