但是,上面的Singleton在代碼一加載的時候就已經建立了,怎么延遲加載呢?想象C#里怎么實現單例的:)采用下面這種模式: 代碼如下: MyNamespace.Singleton = (function() { function constructor() { // All of the normal singleton code goes here. ... } return { getInstance: function() { // Control code goes here. } } })();
具體來說,把創建單例的代碼放到constructor里,在首次調用的時候再實例化: 完整的代碼如下: 代碼如下: MyNamespace.Singleton = (function() { var uniqueInstance; // Private attribute that holds the single instance. function constructor() { // All of the normal singleton code goes here. ... } return { getInstance: function() { if(!uniqueInstance) { // Instantiate only if the instance doesn't exist. uniqueInstance = constructor(); } return uniqueInstance; } } })();