但是,上面的Singleton在代碼一加載的時(shí)候就已經(jīng)建立了,怎么延遲加載呢?想象C#里怎么實(shí)現(xiàn)單例的:)采用下面這種模式: 代碼如下: MyNamespace.Singleton = (function() { function constructor() { // All of the normal singleton code goes here. ... } return { getInstance: function() { // Control code goes here. } } })();
具體來說,把創(chuàng)建單例的代碼放到constructor里,在首次調(diào)用的時(shí)候再實(shí)例化: 完整的代碼如下: 代碼如下: 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; } } })();