<html>
<script>
var Singleton = function() {
var attr = 1, fn = function(){ console.log("I am executed in closure");};
return {
method : function(){ fn(); },
getAttr : function(){ console.log("will be returned: " + attr ); return attr; }
};
}();
Singleton.method();
Singleton.getAttr();
var LazySingleton = function(){
var attr = 2, fn = function(){ console.log("I am LazySingleton function");};
var obj = {
method : function(){ fn(); },
getAttr : function(){ return attr; }
};
function init(){
return obj;
}
return { getInstance: init};
}();
LazySingleton.getInstance().method();
console.log("LazySingleton: " + LazySingleton.getInstance().getAttr());
function Universe() {
if (typeof Universe.instance === 'object') {
return Universe.instance;
}
this.start_time = 0;
this.bang = "Big";
Universe.instance = this;
}
var uni = new Universe();
var uni2 = new Universe();
console.log(uni === uni2);
function Universe2() {
var instance = this;
this.start_time = 0;
this.bang = "Big";
Universe2 = function () {
return instance;
};
}
var un1i = new Universe2();
var un1i2 = new Universe2();
un1i.bang = "123";
console.log(un1i === un1i2);
console.log(un1i2.bang);
var Universe3;
(function () {
var instance;
Universe3 = function Universe3() {
if (instance) {
return instance;
}
instance = this;
this.start_time = 0;
this.bang = "Big";
};
} ());
var a = new Universe3();
var b = new Universe3();
alert(a === b);
a.bang = "123";
alert(b.bang);
</script>
</html>