SoFunction
Updated on 2025-04-12

JavaScript Design Pattern Learning Singleton


/* Basic Singleton. */
var Singleton = {
attribute1: true,
attribute2: 10,
method1: function() {
},
method2: function(arg) {
}
};
One of the main uses of single-piece mode is namespace:
/* GiantCorp namespace. */
var GiantCorp = {};
= {
// A singleton with common methods used by all objects and modules.
};
= {
// An object literal used to store data.
};
= {
// A singleton with page specific methods and attributes.
};
Implement private methods and private variables in single-piece mode using closures:
= (function() {
// Private attributes.
var whitespaceRegex = /\s+/;
// Private methods.
function stripWhitespace(str) {
return (whitespaceRegex, '');
}
function stringSplit(str, delimiter) {
return (delimiter);
}
// Everything returned in the object literal is public, but can access the
// members in the closure created above.
return {
// Public method.
stringToArray: function(str, delimiter, stripWS) {
if(stripWS) {
str = stripWhitespace(str);
}
var outputArray = stringSplit(str, delimiter);
return outputArray;
}
};
})(); // Invoke the function and assign the returned object literal to
// .
Implement Lazy Instantiation single-piece mode:
= (function() {
var uniqueInstance; // Private attribute that holds the single instance.
function constructor() { // All of the normal singleton code goes here.
...
}
return {
getInstance: function() {
if(!uniqueInstance) { // Instantiate only if the instance doesn't exist.
uniqueInstance = constructor();
}
return uniqueInstance;
}
}
})();
().publicMethod1();