Skip to content

Instantly share code, notes, and snippets.

@dsimard
Created August 22, 2011 23:53
Show Gist options
  • Select an option

  • Save dsimard/1163955 to your computer and use it in GitHub Desktop.

Select an option

Save dsimard/1163955 to your computer and use it in GitHub Desktop.
Javascript singleton
function Cats() {
var names = [];
// Get the instance of the Cats class
// If there's none, instanciate one
var getInstance = function() {
if (!Cats.singletonInstance) {
Cats.singletonInstance = createInstance();
}
return Cats.singletonInstance;
}
// Create an instance of the Cats class
var createInstance = function() {
// Here, you return all public methods and variables
return {
add : function(name) {
names.push(name);
return this.names();
},
names : function() {
return names;
}
}
}
return getInstance();
}
function run() {
// Add a new cat
var cat1 = new Cats();
cat1.add("Mistigri");
console.log("cat1 contains 1 cat : " + cat1.names().toString());
// Use another instance
var cat2 = new Cats();
console.log("cat2 contains Mistigri added in cat1 : " + cat2.names().toString());
// Add another cat in the other instance
cat2.add("Felix");
console.log("cat2 contains Mistigri and Felix : " + cat2.names().toString());
console.log("cat1 also contains Mistigri and Felix : " + cat1.names().toString());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment