簡體   English   中英

JavaScript中的單例模式

[英]Singleton Pattern in Javascript

我最近在閱讀Javascript模式 ,談論單例模式時我不理解下面的代碼:

function Universe(){
    var instance;
    Universe=function Universe(){
        return instance;
    };
    Universe.prototype=this;

    //the new Universe below,refers to which one?The original one,
    //or the one:function(){return this;} ??
    instance=new Universe();

    instance.constructor=Universe;

    instance.bang="Big";

    return instance;
}
Universe.prototype.nothing=true;
var uni=new Universe();
Universe.prototype.everything=true;
var uni2=new Universe();

uni===uni2;//true

這里沒有太多的事情。 主要焦點應該放在構造函數上,它為您返回實例化的Universe。 因此,任何調用它的人都將引用同一實例。 注意構造函數如何指向Universe函數。

我不會使用這種模式,因為new關鍵字暗示正在創建一個新實例,這對我來說似乎有些深奧。 在JS中,您可以完美地擁有一個對象文字,通常與名稱空間模式一起使用:

(function(ns, window, undefined) {
    ns.singleton = {
        bang: 'Big'
    };

    window.ns = ns;
})(ns || {}, window);

console.log(window.ns.singleton.bang === 'Big');

當然,這不是真正的單例,但不需要實例化,並且使用它的任何人都將具有相同的值。

有關更多單例實現,請參見Javascript:最佳Singleton模式

您的代碼很亂。

我會使用這種模式:

var universe = function(){

  var bang = "Big"; //private variable

  // defined private functions here    

  return{  //return the singleton object 
    everything : true,
    // or nothing : true, I don't guess your logic

    // public functions here (closures accessing private functions and private variables)
    getBang : function(){ return bang; } 
  };
}();

然后,您可以致電:

alert(universe.everything); // true
alert(universe.getBang()); //true
alert(universe.bang); //Undefined property ! Cause private ;)

因為是單例 ,所以不需要為prototype對象定義共享方法,因為會有一個實例。 (因此是函數表達式而不是函數聲明)。

這種設計的所有優點都是作用域鏈和閉包(公共功能)的好處。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM