2016-01-20 57 views
0

我正在學習JavaScript中的設計模式,我正在通過Singleton設計模式。下面是代碼:JavaScript中的單例實例範圍混淆

var SingletonTester = (function() { 
    // options: an object containing configuration options for the singleton 
    // e.g var options = { name: 'test', pointX: 5}; 
    function Singleton(options) { 
     // set options to the options supplied or an empty object if none provided. 
     options = options || {}; 
     //set the name parameter 
     this.name = 'SingletonTester'; 
     //set the value of pointX 
     this.pointX = options.pointX || 6; 
     //set the value of pointY 
     this.pointY = options.pointY || 10; 
    } 
      // this is our instance holder 
    var instance; 

    // this is an emulation of static variables and methods 
    var _static = { 
     name: 'SingletonTester', 
     // This is a method for getting an instance 
     // It returns a singleton instance of a singleton object 
     getInstance: function (options) { 
      if (instance === undefined) { 
       instance = new Singleton(options); 
      } 
      return instance; 
     } 
    }; 
    return _static; 
})(); 
var singletonTest = SingletonTester.getInstance({ 
    pointX: 5 
}); 
var singletonTest1 = SingletonTester.getInstance({ 
    pointX: 15 
}); 
console.log(singletonTest.pointX); // outputs 5 
console.log(singletonTest1.pointX); // outputs 5 

我不明白爲什麼變量instance得到了一些值時啓動singletonTest1

+0

在JS中,你不需要'Singleton',只需要使用一個全局變量。 –

+0

其次^,但如果你仍然想要一個單例模擬,那麼谷歌爲「JavaScript單身執行者」。有一些Git項目可以做到這一點。無論如何,不​​應該做出正確的判斷。 JS是JS。 – Ingmars

+0

@DavinTryon這已經是單身模式,它工作正常。我的困惑是,當'singletonTest1'啓動時''instance'變量有多值。至少在評論前閱讀這個問題。 –

回答

1

在創建模塊SingletonTester,它也被稱爲:

var SingletonTester = (function() { 
    // ... stuff in here 
    var instance; 
})(); // <--- here 

最後一行是功能應用();。在該應用程序之後,SingletonTester模塊包含它所有的封閉狀態。

由於instance是由SingletonTester關閉,例如關閉了一個屬性是的SingletonTester整個存在活着

便箋:單例模式主要是爲了創建一個線程安全的靜態實例來跨進程共享。由於JavaScript是單線程的,這顯然不是問題。您可以將事情簡單化並使用全局變量。

+0

啊,現在我明白了,感到困惑。當然它是封閉的。非常感謝達文。 –