Repository navigation
Expand file tree
/
Copy pathClosure.js
More file actions
69 lines (52 loc) · 1.47 KB
/
Copy pathClosure.js
File metadata and controls
69 lines (52 loc) · 1.47 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
// closure = A function defined inside of another fuction ,
// the inner function has access to the variables
// and scope of the outer function
// Allow for private variables and state maintainance
// Used frequencly in JS frameworks React , Vue , Angular
function outer(){
let message = "Hello";
function inner(){
console.log(message);
}
inner();
}
message = "GoodBye";
outer();
//---------------------------------------------------------
function createCounter(){
let count = 0;
function increment(){
count++;
console.log(`Count increaded to ${count}`);
}
function getCount(){
return count;
}
return {increment,getCount};
}
const counter = createCounter();
counter.increment();
counter.increment();
counter.increment();
console.log(`The Count Increased to ${counter.getCount}`);
//-------------------------------------------------
function createGame(){
let score =0;
function increasedScore(points){
score+=points;
console.log(`+${points}pts`);
}
function decreasedScore(points){
score-=points;
console.log(`-${points}pts`);
}
function getScore(){
return score;
}
return {increasedScore,decreasedScore,getScore};
}
const game = createGame();
game.increasedScore(5);
game.increasedScore(6);
game.decreasedScore(3);
console.log(`The Score is ${game.getScore()}pts`);