-
Notifications
You must be signed in to change notification settings - Fork 1
/
09 Crazy JS interview on Closures .js
108 lines (100 loc) · 2.26 KB
/
09 Crazy JS interview on Closures .js
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
//Example on closure
function outer() {
var a = 10;
function inner() {
console.log(a);
}
return inner;
}
outer()();//It still remembers the value of a variable.
//Changing postion of variable
function outer() {
// var a=10;
function inner() {
console.log(a);
}
var a = 10;//Even if we morve the position of variable declartion it is still closure
return inner;
}
outer()();
//Changing var to let
function outer() {
// var a=10;
function inner() {
console.log(a);
}
let a = 10;//Even if we change the var to let it is still closure
return inner;
}
outer()();
//Pass an paramerter in outer function
function outer(b) {
function inner() {
console.log(a, b);
}
let a = 10;
return inner;
}
var close = outer("Hello from Akshad");
close();
//Relation of scope chain and closure
function outest() {
function outer(b) {
var c = 20;
function inner() {
console.log(a, b, c);
}
let a = 10;
return inner;
}
return outer;
}
var close = outest()("Hello from Akshad");
close();
//Conflicting name of global variable let in js
function outest() {
function outer(b) {
var c = 20;
function inner() {
console.log(a, b, c);
}
let a = 10;
return inner;
}
return outer;
}
let a = 100;//but it will still print the value of a present in the function scope.
var close = outest()("Hello from Akshad");
close();
//Example of data privacy using closures
function counter() {
count = 0;
return function incrmentCounter() {
count++;
console.log(count);
}
}
//console.log(count);// No one can access this count outside the closure.it will throw error.
var counter1 = counter();
counter1();
counter1();
counter1();
counter1();
//Function Constructor in javascript using closures
function Counter() {
count = 0;
this.incrementCounter = function () {
count++;
console.log(count);
}
this.decrementCounter = function () {
count--;
console.log(count);
}
}
var counter1 = new Counter();
counter1.incrementCounter()
counter1.incrementCounter()
counter1.decrementCounter()
counter1.decrementCounter()
counter1.incrementCounter()