Skip to content

Instantly share code, notes, and snippets.

@crimx
Created April 7, 2016 02:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crimx/74c45025983d817e871a88efa2b0f13e to your computer and use it in GitHub Desktop.
Save crimx/74c45025983d817e871a88efa2b0f13e to your computer and use it in GitHub Desktop.
Make any function singleton
function singletonify(_Class) {
if (typeof singletonify.prototype._singletonifyInstances === 'undefined') {
singletonify.prototype._singletonifyInstances = [];
}
var _instances = singletonify.prototype._singletonifyInstances;
var _index = _instances.push(void(0)) - 1;
function genSingleton() {
if (typeof _instances[_index] !== 'undefined') {
return _instances[_index];
} else {
_Class.apply(_instances[_index] = Object.create(_Class.prototype), arguments);
return _instances[_index];
}
}
genSingleton.prototype = _Class.prototype;
return genSingleton;
}
// test
function Foo(a, b) { this.a = a; this.b = b; }
var Bar = singletonify(Foo);
var f1 = new Bar('a', 'b');
var f2 = new Bar('c', 'd');
console.log(f1, f2);
console.assert(f1 instanceof Bar, 'instanceof Bar');
console.assert(f1 instanceof Foo, 'instanceof Foo');
function Foo0(a, b) { this.a = a; this.b = b; }
Foo0 = singletonify(Foo0);
function Foo1(a, b) { this.a = a; this.b = b; }
Foo1 = singletonify(Foo1);
function Foo2(a, b) { this.a = a; this.b = b; }
Foo2 = singletonify(Foo2);
function Foo3(a, b) { this.a = a; this.b = b; }
Foo3 = singletonify(Foo3);
console.assert(new Foo0('a', 'b') === new Foo0('c', 'd'), '00');
console.assert(new Foo0('e', 'f') === new Foo0('g', 'h'), '01');
console.assert( Foo0('i', 'j') === Foo0('k', 'l'), '02');
console.assert(new Foo1('a', 'b') === Foo1('c', 'd'), '1');
console.assert( Foo2('a', 'b') === new Foo2('c', 'd'), '2');
console.assert( Foo3('a', 'b') === Foo3('c', 'd'), '3');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment