Simplest/Cleanest way to implement singleton in JavaScript?

后端 未结 30 994
名媛妹妹
名媛妹妹 2020-11-22 05:17

What is the simplest/cleanest way to implement singleton pattern in JavaScript?

30条回答
  •  有刺的猬
    2020-11-22 05:41

    Module pattern: in "more readable style". You can see easily which methods are publics and which ones are privates

    var module = (function(_name){
       /*Local Methods & Values*/
       var _local = {
          name : _name,
          flags : {
            init : false
          }
       }
    
       function init(){
         _local.flags.init = true;
       }
    
       function imaprivatemethod(){
         alert("hi im a private method");
       }
    
       /*Public Methods & variables*/
    
       var $r = {}; //this object will hold all public methods.
    
       $r.methdo1 = function(){
           console.log("method1 call 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 init method
    
       return $r; //returning all publics methods
    
    })("module");
    

    now you can use publics methods like

    module.method2(); //-> I'm calling a private method over a public method alert("hi im a private method")

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

提交回复
热议问题