-
Notifications
You must be signed in to change notification settings - Fork 2
/
closures.js
95 lines (80 loc) · 2.07 KB
/
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
function greet(greeting){
return function(name){
console.log('Hello ' + name);
}
}
let greetHi = greet('Hi');
greetHi('Everyone.'); // Hi Everyone.
// Call Stack stores the function call to execute.
// | |
// | |
// | |
// |________________|
// |Global Execution|
// |____Context_____|
// | |
// |________________|
// | greet() | // Execution context of
// | greeting="hi" | greet
// |________________|
// |Global Execution|
// | Context |
// |________________|
// | greetHi() | // Execution context of greetHi.
// |name="everyone" |
// |________________|
// | greeting="hi" | // Execution Context is poped off but greeting is still in memory.
// |________________|
// |Global Execution|
// |____Context_____|
// | greetHi() |
// |name="everyone" | -------.
// |________________| | Eventhough greet function finshes execution
// | greeting="hi" | <------' any function created inside still have reference
// |________________| to greet's memory and it's not garbage collected.
// |Global Execution|
// |____Context_____|
// This phenomenon of closing in all the variables it supposed to have access to
// is called closure
// -Anthony Alicea
// function foo(){
// let functions = [];
// for(var i=0;i<3;i++){
// functions.push(
// function(){
// console.log(i)
// }
// )
// }
// return functions;
// }
// function foo(){
// let functions = [];
// for(let i=0;i<3;i++){
// functions.push(
// function(){
// console.log(i)
// }
// )
// }
// return functions;
// }
function foo(){
var functions = [];
for(var i=0;i<3;i++){
functions.push(
(function(j){
return (
function(){
console.log(j)
}
)
}(i))
)
}
return functions;
}
let fns = foo();
fns[0]();
fns[1]();
fns[2]();