Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
11
rated 0 times [  14] [ 3]  / answers: 1 / hits: 103873  / 11 Years ago, sun, july 21, 2013, 12:00:00

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.


More From » module

 Answers
45

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

jsfiddle for the code above.


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


[#76838] Saturday, July 20, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
pierre

Total Points: 716
Total Questions: 128
Total Answers: 102

Location: Djibouti
Member since Sun, Feb 27, 2022
2 Years ago
pierre questions
Fri, Nov 6, 20, 00:00, 4 Years ago
Fri, Sep 4, 20, 00:00, 4 Years ago
Thu, Jul 18, 19, 00:00, 5 Years ago
Sun, Dec 2, 18, 00:00, 6 Years ago
Fri, Oct 26, 18, 00:00, 6 Years ago
;