2017-01-06 32 views
0

如何在JavaScript中使用IIFE模塊模式編寫單例類? 你可以提供一個例子嗎?如何在JavaScript中使用IIFE模塊模式編寫單例類?

我嘗試過這樣的事情,但是它對x2.getInstance失敗。 根據我的理解,x2.getInstance()應該獲得與x1.getInstance()相同的實例。我如何使用IIFE模塊模式實現這一點?

var x = (function(){ 

    var instance ; 
    var vconstructor = function(){}; 
    //vconstructor.prototype.method1 = function(){} 
    //vconstructor.prototype.method2 = function(){} 
    vconstructor.prototype.getInstance = function(){ 
     if (!instance) { 
      console.log('critical section'); 
      instance = somefunc(); 
      return instance; 
    } 
    }; 

    function somefunc(){ 
     return { "key1": "value1"}; 
    } 

    return vconstructor; 
})(); 

var x1 = new x(); 
console.log('1.'); 
console.log(x1 instanceof x); 
console.log(x1); 
console.log('2.' + x1.getInstance()); 
var x2 = new x(); 
console.log(x2); 
console.log('x2: ' + x2.getInstance()); 

請注意。

回答

0

你可以試試這個:

var Singleton = (function() { 
    var instance; 

    function createInstance() { 
     var object = new Object("I am the instance"); 
     return object; 
    } 

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

function run() { 

    var instance1 = Singleton.getInstance(); 
    var instance2 = Singleton.getInstance(); 

    alert("Same instance? " + (instance1 === instance2)); 
} 
+0

嗯,我想用與IIFE新()的關鍵字,它只是wasnt工作。 – Plankton

+0

我曾試過這個,但在這裏我們只是調用module.api(),它可以工作,但我想用new()來實現;問題是新的,return語句必須是構造函數。如果我們做這樣的事情返回{getInstance:function(){}},它驚天破裂 – Plankton

+0

讓我試試這個問題.. – Sahadev