-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathEp-12-Interview-Clossures.js
More file actions
112 lines (94 loc) · 2.38 KB
/
Ep-12-Interview-Clossures.js
File metadata and controls
112 lines (94 loc) · 2.38 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
// Clossure : function with its lexical scope bundle together forms a clossure.
// Each and every function has access to their parent environment elements.
// function outer (b) {
// var a = 10
// function inner () {
// console.log(a,b);
// }
// return inner
// }
// // outer()()
// var close = outer("hello b")
// close()
function outest () {
var c = 20
function outer (b) {
var a = 10
function inner () {
console.log(a,b,c)
}
return inner
}
return outer
}
var close = outest()("hello b");
close()
// 🟨Advantages of Clossure :
// 🟩 it is used in module pattern
// 🟩 function currying
// 🟩 function memooize, once
// 🟩 data hiding & Encapsulation & data privacy
// ✅ if we have a variable, we want some data privacy over it, so other variables and functions can't access that data
// ------------------
// 🚩Example:
// ------------------
// function counter () {
// var count = 0
// return function incrementCounter () {
// count++
// console.log(count);
// }
// }
// console.log(counter) // Wo'nt work
// var counter1 = counter() // permission to access counter
// counter1()
// counter1()
// var counter2 = counter()
// counter2()
// counter2()
// ----------------------------------
// 🚩 Using constructor Scalable Code
// ----------------------------------
function Counter () {
var count = 0
this.increseCounter = function () {
count++
console.log(count);
}
this.decreseCounter = function () {
count--
console.log(count);
}
}
var counter1 = new Counter()
counter1.increseCounter()
counter1.increseCounter()
counter1.increseCounter()
counter1.decreseCounter()
counter1.decreseCounter()
counter1.decreseCounter()
// 🟨Disadvantages of Clossures :
// 🟩 over consuption of memory
// 🟨Garbage Collector :
// a program in browser or in the js engine which kind of freeze up the unutilized memory
// so whenever there was some unused variables it kind of like just takes it out of memory
// it freeze the memory when it finds that variable not needed.
// 🟨Relation in between Garbage collector and Clossure :
function a () {
var x = 0
return function b () {
console.log(x);
}
}
var y = a()
y()
// 🟨Garbage Collector
function d () {
var e = 0,z = 10
return function b () {
console.log(e);
}
}
var y = d()
y()
// console.log(z); // Garbage collected