|
復(fù)制代碼 代碼如下:
MyNamespace.Singleton = function() {
return {};
}();
比如:
復(fù)制代碼 代碼如下:
MyNamespace.Singleton = (function() {
return { // Public members.
publicAttribute1: true,
publicAttribute2: 10,
publicMethod1: function() {
...
},
publicMethod2: function(args) {
...
}
};
})();
但是,上面的Singleton在代碼一加載的時(shí)候就已經(jīng)建立了,怎么延遲加載呢?想象C#里怎么實(shí)現(xiàn)單例的:)采用下面這種模式:
復(fù)制代碼 代碼如下:
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í)例化:
完整的代碼如下:
復(fù)制代碼 代碼如下:
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;
}
}
})();
JavaScript技術(shù):JavaScript的單例模式 (singleton in Javascript),轉(zhuǎn)載需保留來源!
鄭重聲明:本文版權(quán)歸原作者所有,轉(zhuǎn)載文章僅為傳播更多信息之目的,如作者信息標(biāo)記有誤,請(qǐng)第一時(shí)間聯(lián)系我們修改或刪除,多謝。