用JavaScript实现单例模式的最简单/最干净的方法是什么?


当前回答

对我来说,最干净的方法是:

const singleton = new class {
    name = "foo"
    constructor() {
        console.log(`Singleton ${this.name} constructed`)
    }
}

使用这种语法,您可以确定您的单例是并且将保持惟一的。您还可以享受类语法的甜蜜,并按预期使用它。

(注意,类字段需要节点v12+或现代浏览器。)

其他回答

模块模式:“更具可读性的风格”。您可以很容易地看到哪些方法是公共的,哪些是私有的

var module = (function(_name){
   /* Local Methods & Values */
   var _local = {
      name : _name,
      flags : {
        init : false
      }
   }

   function init(){
     _local.flags.init = true;
   }

   function imaprivatemethod(){
     alert("Hi, I'm a private method");
   }

   /* Public Methods & variables */

   var $r = {}; // This object will hold all public methods.

   $r.methdo1 = function(){
       console.log("method1 calls it");
   }

   $r.method2 = function(){
      imaprivatemethod(); // Calling private method
   }

   $r.init = function(){
      inti(); // Making 'init' public in case you want to init manually and not automatically
   }

   init(); // Automatically calling the init method

   return $r; // Returning all public methods

})("module");

现在你可以使用公共方法,比如

module.method2 ();// ->我正在调用一个私有方法超过一个公共方法警报(“嗨,我是一个私有方法”)

http://jsfiddle.net/ncubica/xMwS9/

我认为我已经找到了用JavaScript编程的最简洁的方法,但您需要一些想象力。我是从《JavaScript: the Good Parts》一书中的一个工作技巧中得到这个想法的。

不用new关键字,你可以这样创建一个类:

function Class()
{
    var obj = {}; // Could also be used for inheritance if you don't start with an empty object.

    var privateVar;
    obj.publicVar;

    obj.publicMethod = publicMethod;
    function publicMethod(){}

    function privateMethod(){}

    return obj;
}

你可以这样实例化上面的对象:

var objInst = Class(); // !!! NO NEW KEYWORD

现在有了这个工作方法,你可以创建一个像这样的单例:

ClassSingleton = function()
{
    var instance = null;

    function Class() // This is the class like the above one
    {
        var obj = {};
        return obj;
    }

    function getInstance()
    {
        if( !instance )
            instance = Class(); // Again no 'new' keyword;

        return instance;
    }

    return { getInstance : getInstance };
}();

现在可以通过调用来获取实例

var obj = ClassSingleton.getInstance();

我认为这是最简洁的方法,因为完整的“类”甚至无法访问。

JavaScript中的单例是使用模块模式和闭包实现的。

下面的代码是不言自明的

// Singleton example.
var singleton = (function() {
  var instance;

  function init() {
    var privateVar1 = "this is a private variable";
    var privateVar2 = "another var";

    function pubMethod() {
      // Accessing private variables from inside.
      console.log(this.privateVar1);
      console.log(this.privateVar2);
      console.log("inside of a public method");
    };
  }

  function getInstance() {
    if (!instance) {
      instance = init();
    }
    return instance;
  };

  return {
    getInstance: getInstance
  }
})();

var obj1 = singleton.getInstance();
var obj2 = singleton.getInstance();

console.log(obj1 === obj2); // Check for type and value.

对我来说,最干净的方法是:

const singleton = new class {
    name = "foo"
    constructor() {
        console.log(`Singleton ${this.name} constructed`)
    }
}

使用这种语法,您可以确定您的单例是并且将保持惟一的。您还可以享受类语法的甜蜜,并按预期使用它。

(注意,类字段需要节点v12+或现代浏览器。)

下面是一个简单的例子来解释JavaScript中的单例模式。

var Singleton = (function() {
    var instance;
    var init = function() {
        return {
            display:function() {
                alert("This is a singleton pattern demo");
            }
        };
    };
    return {
        getInstance:function(){
            if(!instance){
                alert("Singleton check");
                instance = init();
            }
            return instance;
        }
    };
})();

// In this call first display alert("Singleton check")
// and then alert("This is a singleton pattern demo");
// It means one object is created

var inst = Singleton.getInstance();
inst.display();

// In this call only display alert("This is a singleton pattern demo")
// it means second time new object is not created,
// it uses the already created object

var inst1 = Singleton.getInstance();
inst1.display();