Created
March 21, 2012 17:54
-
-
Save danheberden/2150255 to your computer and use it in GitHub Desktop.
Reusable object pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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