design patterns - Javascript Singleton Factory -
so i've got singleton "class" works pretty well:
function base_singleton () { if ( base_singleton.prototype._singletoninstance ) return base_singleton.prototype._singletoninstance; else return base_singleton.prototype._singletoninstance = this; }
this works great. make multiple instances if want, , reflect changes of each other:
var sing1 = new base_singleton(); var sing2 = new base_singleton(); sing1.foo = "bar"; sing2.foo === "bar"; // true
so want able create multiple singleton interfaces, own info. i'm open way of accomplishing this. 2 methods came mind either extending or making factory.
when try extending, new object gets prototype of base_singleton
, it's not extending it's creating instance.
i figure best way via factory can create new object each time:
var singleton_factory = new function () { // let's assume in web environment var global = global || window; /** * build new object singleton functionality. * singleton functionality based https://goo.gl/yfmith * * idea there instance of object shared through * singleton's prototype. can create many 'new' singletons * desire, mirror same prototypical object. * * @param {string} singletonname name of new singleton, , * prototype * @param {object} namespace namespace add new object * * @return {object} newly created singleton */ this.make = function ( singletonname, namespace ) { // default global object defined earlier namespace = namespace || global; // if there shared _singletoninstance, return if ( namespace[singletonname].prototype._singletoninstance ) return namespace[singletonname].prototype._singletoninstance; // if there isn't one, create , return 'this' else return namespace[singletonname].prototype._singletoninstance = this; } }
problem here i'm trying use prototype
on undefined.
how can create factory can create new prototype functionality of base_singleton
?
Comments
Post a Comment