Skip to content

Instantly share code, notes, and snippets.

@quipu
Created June 16, 2014 08:56
Show Gist options
  • Save quipu/6be09cd7847951722096 to your computer and use it in GitHub Desktop.
Save quipu/6be09cd7847951722096 to your computer and use it in GitHub Desktop.
Example code demonstrating the singleton design pattern.
var dom = (function() {
var _counter = 0,
instance;
generateId = function () {
return "customId" + _counter;
};
create = function (tagName, id) {
var el = document.createElement(tagName);
el.id = id || generateId();
return el;
};
// Create a public function containing all the object functions
// we wish to expose
function createInstance() {
return {
generateId : generateId,
create : create
};
}
// Rather than returning public members we return a single
// getInstance() function which either creates an
// instance of the object
// or returns the already created instance, thereby ensuring only one
// instance of the object is created.
return {
getInstance : function() {
// return the existing instance or create then send
return instance || createInstance();
}
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment