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));
}
run();
在上面的代码中,变量实例仅是该函数的本地变量,当我们调用“ Singleton.getInstance()”时。每当变量再次初始化时。那么它如何返回相同的实例。