Skip to content

Instantly share code, notes, and snippets.

@danheberden
Created March 21, 2012 17:54
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 danheberden/2150255 to your computer and use it in GitHub Desktop.
Save danheberden/2150255 to your computer and use it in GitHub Desktop.
Reusable object pattern
/* This is an fn that can:
a) make new objects by itself or with the new keyword using some kind of identifier
b) return a cached object if an object with the same identifier is requested
c) is, itself, one of these objects
d) no id is a global ID
e.g.
var foo = new maker('baz');
var foo1 = maker('baz');
maker('baz') === foo; // true
maker('baz') === foo1; // true
maker('wat') === foo; // false
foo.method === foo1.method; // true
maker.method === maker('nou').method; // true;
*/
var cache = {},
maker = function( identifier, global ){
// no repo was specified, go global
if ( !identifier ) {
return globalMaker;
}
// is there a cache of this repo?
if ( cache[ identifier ] ) {
return cache[ identifier ];
}
// are we operating as a constructor?
if ( this instanceof maker ){
this.identifier = identifier;
if ( global ){
globalMaker = this;
} else {
cache[ identifier ] = this;
}
}
return new maker( identifier );
},
maker( '', global );
maker.method = function(){
return 'foo';
}
maker.prototype = maker;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment