Skip to content

Commit 63d0f05

Browse files
committed
closes #2244
1 parent 6daaaa2 commit 63d0f05

File tree

1 file changed

+14
-9
lines changed
  • 1-js/09-classes/04-private-protected-properties-methods

1 file changed

+14
-9
lines changed

1-js/09-classes/04-private-protected-properties-methods/article.md

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -96,8 +96,9 @@ class CoffeeMachine {
9696
_waterAmount = 0;
9797

9898
set waterAmount(value) {
99-
// "throw new Error" generates an error, we'll cover it later in the tutorial
100-
if (value < 0) throw new Error("Negative water");
99+
if (value < 0) {
100+
value = 0;
101+
}
101102
this._waterAmount = value;
102103
}
103104

@@ -118,7 +119,7 @@ let coffeeMachine = new CoffeeMachine(100);
118119
coffeeMachine.waterAmount = -10; // Error: Negative water
119120
```
120121

121-
Now the access is under control, so setting the water below zero fails.
122+
Now the access is under control, so setting the water amount below zero becomes impossible.
122123

123124
## Read-only "power"
124125

@@ -160,7 +161,7 @@ class CoffeeMachine {
160161
_waterAmount = 0;
161162
162163
*!*setWaterAmount(value)*/!* {
163-
if (value < 0) throw new Error("Negative water");
164+
if (value < 0) value = 0;
164165
this._waterAmount = value;
165166
}
166167
@@ -200,19 +201,23 @@ class CoffeeMachine {
200201
*/!*
201202

202203
*!*
203-
#checkWater(value) {
204-
if (value < 0) throw new Error("Negative water");
205-
if (value > this.#waterLimit) throw new Error("Too much water");
204+
#fixWaterAmount(value) {
205+
if (value < 0) return 0;
206+
if (value > this.#waterLimit) return this.#waterLimit;
206207
}
207208
*/!*
208209

210+
setWaterAmount(value) {
211+
this.#waterLimit = this.#fixWaterAmount(value);
212+
}
213+
209214
}
210215

211216
let coffeeMachine = new CoffeeMachine();
212217

213218
*!*
214219
// can't access privates from outside of the class
215-
coffeeMachine.#checkWater(); // Error
220+
coffeeMachine.#fixWaterAmount(123); // Error
216221
coffeeMachine.#waterLimit = 1000; // Error
217222
*/!*
218223
```
@@ -233,7 +238,7 @@ class CoffeeMachine {
233238
}
234239

235240
set waterAmount(value) {
236-
if (value < 0) throw new Error("Negative water");
241+
if (value < 0) value = 0;
237242
this.#waterAmount = value;
238243
}
239244
}

0 commit comments

Comments
 (0)