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());
請注意。
嗯,我想用與IIFE新()的關鍵字,它只是wasnt工作。 – Plankton
我曾試過這個,但在這裏我們只是調用module.api(),它可以工作,但我想用new()來實現;問題是新的,return語句必須是構造函數。如果我們做這樣的事情返回{getInstance:function(){}},它驚天破裂 – Plankton
讓我試試這個問題.. – Sahadev