singleton object in javascript

singleton object in javascript

by shubh0602

JavaScript

var singelton = (function() {
  var instance;

  var _createInstance = function() {
    var obj = {
      Id: null,
      Name: null
    };
    return obj;
  };

  var _getInstance = function() {
    if (!instance) {
      instance = _createInstance();
    }
    return instance;
  };
  
  return {
  	getInstance : _getInstance
  }
})();
var object1 = singelton.getInstance();
object1.Id = 1;
object1.Name = "Shubh";


var object2 = singelton.getInstance();
object2.Id = 2;
object2.Name = "Dasgupta";

console.log(object1);
console.log(object2);
console.log(object1 === object2);