Thursday, 21 December 2017

JavaScript module pattern with example

itemprop="text">



I can't find
any accessible examples showing how two (or more) different modules are connected to
work together.



So, I'd like to ask whether
anyone has time to write an example explaining how modules work
together.



Answer




In order to approach to Modular design
pattern, you need to understand these concept
first:



Immediately-Invoked Function Expression
(IIFE):




(function()
{
// Your code goes here

}());


There
are two ways you can use the functions. 1. Function declaration 2. Function
expression.



Here are using function
expression.




What is
namespace?
Now if we add the namespace to the above piece of code then



var anoyn = (function()
{
}());


What
is closure in JS?



It means if we declare any
function with any variable scope/inside another function (in JS we can declare a
function inside another function!) then it will count that function scope always. This
means that any variable in outer function will be read always. It will not read the
global variable (if any) with the same name. This is also one of the objective of using
modular design pattern avoiding naming
conflict.




var scope =
"I am global";
function whatismyscope() {
var scope = "I am just a
local";
function func() {return scope;}
return
func;
}
whatismyscope()()



Now
we will apply these three concepts I mentioned above to define our first modular design
pattern:



var modularpattern =
(function() {
// your module code goes here
var sum = 0
;

return {
add:function() {
sum = sum +
1;
return sum;

},
reset:function()
{
return sum = 0;
}
}

}());
alert(modularpattern.add()); // alerts:
1
alert(modularpattern.add()); // alerts:
2
alert(modularpattern.reset()); // alerts:
0



href="http://jsfiddle.net/EkxN7/" rel="noreferrer">jsfiddle for the code
above.



The objective is to hide the
variable accessibility from the outside
world.



Hope this helps. Good
Luck.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print ...