-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclosure.js
More file actions
65 lines (44 loc) · 988 Bytes
/
closure.js
File metadata and controls
65 lines (44 loc) · 988 Bytes
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
let n = 'Sergio';
function sayHi(name) {
console.log('Hi', name);
console.log('n =', n);
}
n = 'Peter';
sayHi(n); // ?
let surname = 'Daniels';
function makeWorker() {
const name = 'Jack';
return function () {
console.log(name, surname);
};
}
const name = 'Tom';
surname = 'Reacher';
const worker = makeWorker();
worker(); // ?
// A variable is a property of a special internal object, associated with the currently executing block/function/script.
// Working with variables is actually working with the properties of that object.
function random() {
let r = Math.random();
return function fun() {
console.log(r);
}
}
let f1 = random();
let f2 = random();
let f3 = random();
f1();
f2();
f3();
// ?
function makeCounter() {
let count = 0;
return function () {
return count++;
};
}
const counter = makeCounter();
console.log(counter()); // 0
console.log(counter()); // 1
console.log(counter()); // 2
// https://javascript.info/closure