<script> var cct = 5; //1st way var singleton1 = { count: 0, add: function () { this.count++; } }; for (var i = 0; i < cct; i++) { singleton1.add(); console.log(singleton1.count); } console.log('================='); //2nd way var singleton2 = function () { return { count: 0, add: function () { this.count++; } }; } var s2 = singleton2(); for (var i = 0; i < cct; i++) { s2.add(); console.log(s2.count); } console.log('================='); //3rd way (lazy load) var singleton3 = (function () { function init() { return { count: 0, add: function () { this.count++; } }; } var instance; return { getInstance: function () { if (!instance) { instance = init(); } return instance; } }; })(); for (var i = 0; i < cct; i++) { singleton3.getInstance().add(); console.log(singleton3.getInstance().count); } console.log('================='); //the best way var singleton4 = (function () { function sst() { this.count = 0; this.add = function () { this.count++; } } var instance; return { getInstance: function () { if (!instance) { instance = new sst(); } return instance; } }; })(); for (var i = 0; i < cct; i++) { singleton4.getInstance().add(); console.log(singleton4.getInstance().count); } console.log('================='); function singleton5() { if (typeof singleton5.instance === 'object') { return singleton5.instance; } this.count = 0; this.add = function () { this.count++; }; singleton5.instance = this; } for (var i = 0; i < cct; i++) { var dd = new singleton5(); dd.add(); console.log(dd.count); } console.log('================='); function singleton6() { var instance = this; this.count = 0; this.add = function () { this.count++; }; singleton6 = function () { return instance; } } for (var i = 0; i < cct; i++) { var dd = new singleton6(); dd.add(); console.log(dd.count); } console.log('================='); function singleton7() { var instance; singleton7 = function singleton7() { return instance; }; instance = new singleton7(); instance.constructor = singleton7; instance.count = 0; instance.add = function () { instance.count++; }; return instance; } for (var i = 0; i < cct; i++) { var dd = singleton7(); dd.add(); console.log(dd.count); } console.log('================='); var singleton8; (function () { var instance; singleton8 = function singleton8() { if (instance) { return instance; } instance = this; this.count = 0; this.add = function () { this.count++; }; } }()); for (var i = 0; i < cct; i++) { var dd = new singleton8(); dd.add(); console.log(dd.count); } console.log('================='); </script>