I had written a non-prototype several years ago like this:
var _singletons = []; // for storing singleton instances of objects Function.prototype.singleton = function (o) { if(!_singletons[this.name]) { _singletons[this.name] = o; return false; } return true; } Function.prototype.getSingleton = function () { return _singletons[this.name]; } then you define a class like this: function AClass() { if AClass.singleton(this) return AClass.getSingleton(); this.a = a; /* etc */ } That way you can call var a = new AClass() as many times as you like and it'd return the same object instance every time. Which I think is close to a real singleton instance of an object. But I don't think you could do that readily with Prototype using the Class.create() mechanism. On 22/05/06, Nicolas Terray <[EMAIL PROTECTED]> wrote:
On 5/22/06, Grzesiek Slusarek <[EMAIL PROTECTED]> wrote: > Hello all. I'm writing my own object using prototype and I > wonder how you write and call only one instance of class. Can > anyone share his idea of singleton? > thanks > Gregor > Here is my proposal : ---8<---------------------- <script> var Foo = Class.create(); Object.extend(Foo.prototype, { initialize: function() { this.a = 5; } }); Object.extend(Foo, { instance: function() { if (!this._instance) { this._instance = new Foo(); } return this._instance; } }); var o1 = Foo.instance(); var o2 = Foo.instance(); alert(o1.a + ' ' + o2.a); o2.a = 10; alert(o1.a + ' ' + o2.a); </script> ---8<---------------------- Anyway it is not a real singleton since it is possible to call the constructor outside from instance() Furthermore, by hacking Foo, I do not know if I break something by adding _instance and instance() :-\ Yours, Nicolas Terray _______________________________________________ Rails-spinoffs mailing list Rails-spinoffs@lists.rubyonrails.org http://lists.rubyonrails.org/mailman/listinfo/rails-spinoffs
-- Andrew Tetlaw htp://tetlaw.id.au
_______________________________________________ Rails-spinoffs mailing list Rails-spinoffs@lists.rubyonrails.org http://lists.rubyonrails.org/mailman/listinfo/rails-spinoffs