-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathClosureProblemInDevelopment.js
More file actions
99 lines (57 loc) · 2.18 KB
/
Copy pathClosureProblemInDevelopment.js
File metadata and controls
99 lines (57 loc) · 2.18 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
/** Common Closure problem in development
* Given 10 html elements, what's the output on the console if I click on the third item?
**/
var items = document.querySelectorAll('.items');
for (var i = 0, max = items.length; i < max; i++) {
var element = items[i];
element.addEventListener('click', function() {
console.log('you clicked on element number ' + i);
});
}
// It will be 10 ..... Why?
// How to fix this behavior?
// One way using inline IIFE it will create closure and keep the i scope as reference
// This will solve the problem but not great way
var items = document.querySelectorAll('.items');
for (var i = 0, max = items.length; i < max; i++) {
var element = items[i];
(function(i) {
element.addEventListener('click', function() {
console.log('you clicked on element number ' + i);
});
})(i)
}
// Another way similar with little addition to present scenario but still using inline anonymous func
var body = document.getElementsByTagName('body')[0];
for (var i = 0, max = 5; i < max; i++) {
var div = document.createElement('div');
div.className = "items";
div.setAttribute('style', 'width: 100%; height: 60px; margin-bottom: 30px; background-color: #000; cursor: pointer')
body.appendChild(div)
}
var items = document.querySelectorAll('.items');
for (var i = 0, max = items.length; i < max; i++) {
var element = items[i];
element.addEventListener('click', (function(n) {
return function() {
alert('you clicked on element number ' + n);
}
})(i));
}
// Here we will break the code little , will use closure but not inline or IIFE
var items = document.querySelectorAll('.items');
for (var i = 0, max = items.length; i < max; i++) {
var element = items[i];
element.addEventListener('click', createLog(i));
}
function createLog(i) {
return function logLocal() {
console.log('you clicked on element number' + i);
}
}
/**if we can use let in this place we can solve the scope problem like this
for (var i = 0; i < letNode.length; i++) {
let j = i;
letNode[i].addEventListener('click', function() { console.log(j); }
}
**/