Madav
Madav

Reputation: 311

Creating Objects with the references of a function's private functions

I came across a snippet and I doubt it can be written in a straightforward way. Could someone please tell me what is the difference between the below two snippets:

var printer = (function () {
  var printerInstance;
  var obj = {
     f1: function() {},
     f2: function() {}
  };
  return {
     getInstance: function() {
       if(!printerInstance) {
         printerInstance = obj;
       }
       return printerInstance;
     }
   };
})();

And

var printer = (function () {
     var printerInstance;
     function create() {
       function f1() {}
       function f2() {}
       return {
          f1: f1,
          f2: f2
       }
     }

     return {
       getInstance: function() {
         if(!printerInstance) {
           printerInstance = create();
         }
         return printerInstance;
       }
     };
})();

I did not understand why the object has been created inside a function in the second example. Please clarify.

Upvotes: 0

Views: 26

Answers (1)

Ramzi Khahil
Ramzi Khahil

Reputation: 5052

Well, the first one has one object called obj for all calls, the second one creates a new one for every call.

So for example say that it is :

var obj = {
   var counter = 0;
   f1: function() { return counter++; },
   f2: function() {}
};

and the second one is:

function create() {
  var counter = 0;
  function f1() { return counter++; }
  function f2() {}
  return {
     f1: f1,
     f2: f2
  }
}

In the first case, there is one object with one counter which will be referenced by all getInstance invocations (where printerInstance equals null). So this is more like a Singleton.

In the second case, each invocation of getInstance will have it's own counter and count independantly.

Upvotes: 1

Related Questions