javascript singleton question

前端 未结 10 2080
闹比i
闹比i 2020-12-12 20:08

I just read a few threads on the discussion of singleton design in javascript. I\'m 100% new to the Design Pattern stuff but as I see since a Singleton by definition won\'t

10条回答
  •  北荒
    北荒 (楼主)
    2020-12-12 20:20

    The singleton pattern is implemented by creating a class with a method that creates a new instance of the class if one does not exist. If an instance already exists, it simply returns a reference to that object. 1

    (function (global) {
    
         var singleton;
    
         function Singleton () {
             // singleton does have a constructor that should only be used once    
             this.foo = "bar";
             delete Singleton; // disappear the constructor if you want
         }
    
         global.singleton = function () {
             return singleton || (singleton = new Singleton());
         };
    
    })(window);
    
    var s = singleton();
    console.log(s.foo);
    
    var y = singleton();
    y.foo = "foo";
    console.log(s.foo);
    

    You don't just declare the singleton as an object because that instantiates it, it doesn't declare it. It also doesn't provide a mechanism for code that doesn't know about a previous reference to the singleton to retrieve it. The singleton is not the object/class that is returned by the singleton, it's a structure. This is similar to how closured variables are not closures, the function scope providing the closure is the closure.

提交回复
热议问题