-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIIFE.js
142 lines (113 loc) · 2.57 KB
/
IIFE.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
// IIFE (Immediately Invoked Function Expression) OR (Self Invoking Function)
(function(){
console.log("IIFE ");
})(); // ()(); // In 1st bracket function then 2nd bracket is the function call.
IIFE
/*
USED because of 2 reasons.
1. When we don't want to recall the parent function for re-allocation.
2. This method is used before let. ()
*/
// 1st reason...
// ISSUE with closure is that if we recalled the init() then the value get reset.
function init(){
var count = 0; // Local Variable
function counter(){
count++;
return count;
}
return counter;
}
var t = init(); it's perfect here
t();
1
t();
2
t();
3
t();
4
t();
5
t = init(); // When we recalled this init function, the count value vanishes. // this is the issue.
t(); // re allocation of count value.
1
t();
2
t();
3
// SOLUTION Here we can use IIFE.
// we removed the function name... so now there is no chance to recall the function...
var g = (function (){
var count = 0; // Local Variable
function counter(){
count++;
return count;
}
return counter;
})();
g; // here g contains returned function.
ƒ counter(){
// var count = 0; // Local Variable
count++;
return count;
}
g();
1
g();
2
g();
3
g();
4
g();
5
g(); // now there is no way to resest the count value.
6
// Using VAR.
function scope(){
console.log(" i is ", i); // undefined
for(var i = 1; i<=5; i++){
console.log("I is ", i);
}
console.log("I is ", i); // 6
}
scope();
i is undefined
I is 1
I is 2
I is 3
I is 4
I is 5
I is 6 // It's clear that there is no blocking scope of var.
// When let is there in ES6(2015).
// let has block level scope, still hoisting is done.
function scope(){
console.log(" i is ", i); // Error
for(let i = 1; i<=5; i++){
console.log("I is ", i);
}
console.log("I is ", i); // Error
}
scope();
VM566:2 Uncaught ReferenceError: i is not defined
at scope (<anonymous>:2:27)
at <anonymous>:1:1
scope @ VM566:2
(anonymous) @ VM589:1
// BEFORE LET we use IIFE to get the feel of block level scope
function scope(){
console.log(" i is ", i); // Error
(function(){
for(var i = 1; i<=5; i++){ // still hoisting is done but we have limited it in IIFE function call
console.log("I is ", i);
}
})();
console.log("I is ", i); // Error
}
scope();
VM615:2 Uncaught ReferenceError: i is not defined
at scope (<anonymous>:2:27)
at <anonymous>:1:1
scope @ VM615:2
(anonymous) @ VM647:1