-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path2_3_closures.js
executable file
·102 lines (82 loc) · 2.4 KB
/
2_3_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
"use strict";
chapter("Closures");
section("Functions with state");
function incrementor(step) {
let n = 0;
return function() {
n += step;
return n;
}
}
let inc = incrementor(10);
println("n and step are captured in closure");
println(" inc() = " + inc());
println(" inc() = " + inc());
println(" inc() = " + inc());
let inc2 = incrementor(5);
println("Each incrementor has it's own state");
println(" inc() = " + inc() + " " + inc2());
println(" inc() = " + inc() + " " + inc2());
println(" inc() = " + inc() + " " + inc2());
section("Be careful");
println("addersVar shares same var i:");
function addersVar(n) {
let a = [];
let i; // Declared before loop
for (i = 0; i < n; i++) {
a.push(function(v) { return i + v; });
}
println("i = " + i);
return a;
}
a = addersVar(3);
for (let j = 0; j < a.length; j++) {
println(" addersVar[" + j + "] adds " + a[j](0));
}
section("Intermediate function trick");
println("addersFun has a copy of var i named w:");
function addersFun(n) {
let a = [];
for (let i = 0; i < n; i++) {
a.push(
(function(w) {
return function(v) { return w + v; }
})(i) // Call of declared intermediate function
);
}
return a;
}
const adder = addersFun(3);
for (let j = 0; j < a.length; j++) {
println(" addersFun[" + j + "] adds " + adder[j](0));
}
println();
section("Use let");
println("No issues with let in loop:");
function addersLet(n) {
let a = [];
for (let i = 0; i < n; i++) {
a.push(function(v) { return i + v; });
}
return a;
}
a = addersLet(3);
for (let j = 0; j < a.length; j++) {
println(" addersLet[" + j + "] adds " + a[j](0));
}
section("Common shared state");
function PrivatePoint(x, y) {
println("Constructor called");
let z = 0;
this.getX = function() { return x; };
this.setX = function(value) { x = value; };
this.getY = function() { return y; };
this.setY = function(value) { y = value; };
this.getZ = function() { return z; };
this.setZ = function(value) { z = value; };
}
let privatePoint = new PrivatePoint(10, 20);
dumpObject("privatePoint", privatePoint);
privatePoint.setX(100);
privatePoint.setZ(1000);
dumpObject("Modified privatePoint", privatePoint);