2012-11-15 41 views
-1

我讀的Javascript模式 recently.And我不明白下面的代碼,當談到單例模式:Singleton模式在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 
+2

關於這個例子的具體問題是什麼? – Brad

+0

這看起來不太複雜......我會用其他模式。 –

+0

@FelixKling肯定我會用其他方式,如使用closures.I只是不明白的代碼,所以我問你們... – user1825777

回答

2

不多回事。主要重點應該放在構造函數上,它會爲你返回一個實例化的Universe。所以任何調用它的人都會參考相同的實例。注意構造函數是如何指向Universe函數的。

我不會使用這種模式,因爲新的關鍵字意味着正在創建一個新的實例,而且這對我的口味來說似乎有點太深奧。在JS可以完美只是有一個對象的文字,往往一個命名空間模式中使用:

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

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

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

當然,這是不是一個真正的單身人士,但它並不需要被實例化,任何人都誰使用它會具有相同的值。

更多單身的實現,見Javascript: best Singleton pattern

0

你的代碼是凌亂。

我會用這個模式:

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對象,因爲會有一個例子。 (因此函數表達式而不是函數聲明)。

這種設計的美妙之處在於範圍鏈和關閉(公共功能)的好處。