1

Which one is better to implement in revealing modular pattern in javascript:

  1. Having a self invoking function which will get intialized just once at the time JS gets rendered, like this:

<div id="output">
</div>

<script>
   var calculator = function()
{
        add = function(x,y){
           return x+y;
        };        
        return { add:add };
}();

document.getElementById("output").innerHTML = calculator.add(5,3);;


</script>
---- OR -----
  1. Having a constructor to do this like:

<div id="output">
</div>

<script>
  var calculator = function()
  {
        add = function(x,y){
             return x+y;
          };
          return { add:add };
  };
    document.getElementById("output").innerHTML = new calculator().add(5,3); 
</script>

In 1st, benefit I read is that each function will be initialized just once while in 2nd, we will have copies of function for each object initialized.

But the problem in 1st is that it will do some work to make that single copy during the JS load time.

I am confused why would we have multiple copies of function in memory in case2 as memory should be allocated to variables and not functions.

Which of these 2 approach is correct and how to decide which to pick when?

Sahil Sharma
  • 3,847
  • 6
  • 48
  • 98
  • The first pattern is equivalent of a singleton pattern. If you want to share some resources you use modular pattern to create a single instance and make everyone use that instance. For example a DB connection – marvel308 Aug 13 '17 at 15:59
  • @marvel308: what about memory allocation? How does memory get allocated for these two? – Sahil Sharma Aug 13 '17 at 16:01
  • I would suggest go through https://developer.mozilla.org/en-US/docs/Web/JavaScript/Memory_Management . and read how does new keyword allocate memory and about garbage collection – marvel308 Aug 13 '17 at 16:07

1 Answers1

0

3) a simple js object? :

var calculator = {
  add(a,b){
   return a+b;
  }
};

alert(calculator.add(1,2))

As you neither want multiple instances ( which the second approach is good for) and youre not having private variables ( which a closure is good for), the upper is probably the way to go.

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151