Which one is better to implement in revealing modular pattern in javascript:
- 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>
- 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?