如何使用IIFE模块模式在javascript中编写单例类? 你能提供一个例子吗?
我尝试了类似的东西,但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());
请告知。
答案 0 :(得分:0)
你可以试试这个:
var Singleton = (function () {
var instance;
function createInstance() {
var object = new Object("I am the instance");
return object;
}
return {
getInstance: function () {
if (!instance) {
instance = createInstance();
}
return instance;
}
};
})();
function run() {
var instance1 = Singleton.getInstance();
var instance2 = Singleton.getInstance();
alert("Same instance? " + (instance1 === instance2));
}