Search code examples
javascriptsingletonecmascript-5

Why my singleton wont work?


I'm beginner on JS, trying to understand how singleton works, and after reading much about so many singleton pattern, I conclude that the following singleton pattern would work,

var singletonIns = (function() {
  var instance;
  function init() {
    var _pvtVar = 123;
    var pubVar = 111;
    var logPvt = function() {
      console.log(_pvtVar);
    };
    
    return {
      pubVar : pubVar,
      logPvt : logPvt
    };
  }
  return {
    getInstance : function() {
      if (!instance) {
        instance = init();
      } else {
        return instance;
      }
    }
  };
})();

It does't throw any error on runtime.

However, when i run this code var abc = singletonIns.getInstance() it returns undefined, and we cannot access abc.pubVar, why is that?

Please explained like I'm five yo.

Thanks in advance.


Solution

  • if (!instance) {
        instance = init();
    

    ... and then what? then you don't return anything. Add return instance; after that and you'll be fine.

    You return the instance when it's initiated, but if it's not you just assign it and not return.