forked from bittu1040/JavaScript-Coding-and-Notes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodule-pattern.js
More file actions
53 lines (43 loc) · 1.07 KB
/
module-pattern.js
File metadata and controls
53 lines (43 loc) · 1.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// module pattern
// The Module Pattern in JavaScript is a way to encapsulate code into independent, reusable modules.
// It allows you to organize your code, keep variables and functions private, and expose only the necessary functionality to the outside world.
// using IIFE
var Calc= (function(){
// private functions and variables
var result= 0;
function add(a,b){
return a+b;
}
function substract(a,b){
return a-b;
}
// public functions
return {
add: function(a,b){
result= add(a,b);
},
substract: function(a,b){
result= substract(a,b);
},
getResult: function(){
return result;
}
}
})();
Calc.add(4,5);
console.log(Calc.getResult()); // 9
// Without using IIFE
var Calculator= {
result: 0,
add: function(a,b){
this.result= a+b;
},
substract: function(a,b){
this.result= a-b;
},
getResult: function(){
return this.result;
}
}
Calculator.add(1,2);
console.log(Calculator.getResult()); // 3