/
6_40.js
122 lines (99 loc) · 2.51 KB
/
6_40.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
// ...
class Bicycle {
constructor(opts = {}) {
this._size = opts.size;
this._chain = opts.chain || this.default_chain();
this._tire_size = opts.tire_size || this.default_tire_size();
}
get size() { return this._size; }
get chain() { return this._chain; }
get tire_size() { return this._tire_size; }
spares() {
return {
tire_size: this.tire_size,
chain: this.chain,
};
}
default_chain() {
return '11-speed';
}
default_tire_size() {
throw new Error('Not implemented');
}
}
class RoadBike extends Bicycle {
constructor(opts = {}) {
super(opts);
this._tape_color = opts.tape_color;
}
get tape_color() { return this._tape_color; }
spares() {
return Object.assign({}, super.spares(), {
tape_color: this.tape_color,
});
}
default_tire_size() {
return '23';
}
}
class MountainBike extends Bicycle {
constructor(opts = {}) {
super(opts);
this._front_shock = opts.front_shock;
this._rear_shock = opts.rear_shock;
}
get front_shock() { return this._front_shock; }
get rear_shock() { return this._rear_shock; }
spares() {
return Object.assign({}, super.spares(), {
front_shock: this.front_shock,
});
}
default_tire_size() {
return '2.1';
}
}
const road_bike = new RoadBike({
size: 'M',
tape_color: 'red',
});
console.log(road_bike.tire_size); // => 23
console.log(road_bike.chain); // => 11-speed
const mountain_bike = new MountainBike({
size: 'S',
front_shock: 'Manitou',
rear_shock: 'Fox',
});
console.log(mountain_bike.tire_size); // => 2.1
console.log(mountain_bike.chain); // => 11-speed
class RecumbentBike extends Bicycle {
constructor(opts = {}) {
/*
* ADAPTATION: JavaScript will not allow you to forget to send `super`, so
* the error shown here will not be about tire_size not getting initialized,
* as in the Ruby example.
*
* Instead this will result in a "ReferenceError: Must call super
* constructor..."
*/
this._flag = opts.flag; // forgot to send `super`
}
get flag() { return this._flag; }
spares() {
return Object.assign({}, super.spares(), {
flag: this.flag,
});
}
default_chain() {
return '10-speed';
}
default_tire_size() {
return '28';
}
}
const bent = new RecumbentBike({
flag: 'tall and orange',
});
// => ReferenceError: Must call super constructor in derived class before accessing 'this' or returning from derived constructor
// at new RecumbentBike ...
console.log(bent.spares());