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
[email protected]
http://lists.rubyonrails.org/mailman/listinfo/rails-spinoffs

Reply via email to