/
3_35.js
96 lines (82 loc) · 2 KB
/
3_35.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
class Wheel {
constructor(rim, tire) {
this._rim = rim;
this._tire = tire;
}
get rim() { return this._rim; }
get tire() { return this._tire; }
diameter() {
return this.rim + (this.tire * 2);
}
}
/*
* KEYWORD ARGS
* keyword arg with simple defaults
*
* NOTE: Here, we're combining destructuring with function defaults to
* accomplish something similar to keyword args with default values.
*
* SEE: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
* SEE: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters
*/
class Gear {
constructor({ chainring = 40, cog = 18, wheel }) {
this._chainring = chainring;
this._cog = cog;
this._wheel = wheel;
}
get chainring() { return this._chainring; }
get cog() { return this._cog; }
get wheel() { return this._wheel; }
// ...
gear_inches() {
return this.ratio() * this.wheel.diameter();
}
ratio() {
return this.chainring / this.cog;
}
}
console.log(new Gear({
wheel: new Wheel(26, 1.5)
}).chainring);
// => 40;
/*
* KEYWORD ARGS
* keyword arg with defaults
*
* NOTE: Sandi's point here is that the `constructor` executes in the new
* instance of Gear, so it should be able to send messages to itself.
*/
class GearWithDefaultMethod {
constructor({
chainring = this.default_chainring(),
cog = 18,
wheel
}) {
this._chainring = chainring;
this._cog = cog;
this._wheel = wheel;
}
get chainring() { return this._chainring; }
get cog() { return this._cog; }
get wheel() { return this._wheel; }
default_chainring() {
return (100 / 2) - 10;
}
// ...
gear_inches() {
return this.ratio() * this.wheel.diameter();
}
ratio() {
return this.chainring / this.cog;
}
}
console.log(new GearWithDefaultMethod({
wheel: new Wheel(26, 1.5)
}).chainring);
// => 40
console.log(new GearWithDefaultMethod({
chainring: 52,
wheel: new Wheel(26, 1.5)
}).chainring);
// => 52