Skip to content

Instantly share code, notes, and snippets.

@coiscir
Last active September 20, 2022 23:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save coiscir/5115095 to your computer and use it in GitHub Desktop.
Save coiscir/5115095 to your computer and use it in GitHub Desktop.
JavaScript Singletons
var myWorld = (function () {
var instance;
function myWorld() {
if (instance != null) return instance;
if (!(this instanceof myWorld)) return new myWorld();
instance = this;
var myPrivate = 1;
this.do1 = function () {
alert(myPrivate);
};
}
return myWorld;
})();
var a = myWorld();
var b = myWorld();
console.log(a === b);
var myWorld = (function () {
var instance = new myWorld();
function myWorld() {
if (instance != null) {
throw new Error('`myWorld` is a singleton. Use `myWorld.instance`.');
}
var myPrivate = 1;
this.do1 = function () {
alert(myPrivate);
};
}
Object.defineProperty(myWorld, 'instance', {
get: function () {
return instance;
},
enumerable: true
});
return myWorld;
})();
try {
console.log('Should never see this:', new myWorld());
} catch (e) {
console.log('Error as expected:', e.message);
}
var a = myWorld.instance;
var b = myWorld.instance;
console.log(a === b);
var myWorld = (function () {
var instance;
function myWorld() {
if (instance != null) return instance;
instance = this;
var myPrivate = 1;
this.do1 = function () {
alert(myPrivate);
};
}
return myWorld;
})();
var a = new myWorld();
var b = new myWorld();
console.log(a === b);

From http://stackoverflow.com/a/15196301/:

p.s. i'll be glad to hear you solution to my other question stackoverflow.com/questions/15274927/…. ( maybe you have a better solution). Royi Namir 2013-03-08 07:03:32Z

The answers do include good examples of both eagerly-loaded/instant (e.g., jantimon, SLaks) and lazy-loaded singletons (e.g., Kolink).

Though, for a few variations on lazy-loaded: :)

It is possible to return the instance (single-instance-constructor.js) each time, but this will probably be confusing unless it's not actually new (constructor-as-function.js). :)

A possible ES5+ variant would be to use a get-only "static" property (readonly-static-property.js).

@cheeseonamonkey
Copy link

Nice 😎🤞

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment