closes #2244
This commit is contained in:
parent
6daaaa224f
commit
63d0f055fc
1 changed files with 14 additions and 9 deletions
|
@ -96,8 +96,9 @@ class CoffeeMachine {
|
|||
_waterAmount = 0;
|
||||
|
||||
set waterAmount(value) {
|
||||
// "throw new Error" generates an error, we'll cover it later in the tutorial
|
||||
if (value < 0) throw new Error("Negative water");
|
||||
if (value < 0) {
|
||||
value = 0;
|
||||
}
|
||||
this._waterAmount = value;
|
||||
}
|
||||
|
||||
|
@ -118,7 +119,7 @@ let coffeeMachine = new CoffeeMachine(100);
|
|||
coffeeMachine.waterAmount = -10; // Error: Negative water
|
||||
```
|
||||
|
||||
Now the access is under control, so setting the water below zero fails.
|
||||
Now the access is under control, so setting the water amount below zero becomes impossible.
|
||||
|
||||
## Read-only "power"
|
||||
|
||||
|
@ -160,7 +161,7 @@ class CoffeeMachine {
|
|||
_waterAmount = 0;
|
||||
|
||||
*!*setWaterAmount(value)*/!* {
|
||||
if (value < 0) throw new Error("Negative water");
|
||||
if (value < 0) value = 0;
|
||||
this._waterAmount = value;
|
||||
}
|
||||
|
||||
|
@ -200,19 +201,23 @@ class CoffeeMachine {
|
|||
*/!*
|
||||
|
||||
*!*
|
||||
#checkWater(value) {
|
||||
if (value < 0) throw new Error("Negative water");
|
||||
if (value > this.#waterLimit) throw new Error("Too much water");
|
||||
#fixWaterAmount(value) {
|
||||
if (value < 0) return 0;
|
||||
if (value > this.#waterLimit) return this.#waterLimit;
|
||||
}
|
||||
*/!*
|
||||
|
||||
setWaterAmount(value) {
|
||||
this.#waterLimit = this.#fixWaterAmount(value);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
let coffeeMachine = new CoffeeMachine();
|
||||
|
||||
*!*
|
||||
// can't access privates from outside of the class
|
||||
coffeeMachine.#checkWater(); // Error
|
||||
coffeeMachine.#fixWaterAmount(123); // Error
|
||||
coffeeMachine.#waterLimit = 1000; // Error
|
||||
*/!*
|
||||
```
|
||||
|
@ -233,7 +238,7 @@ class CoffeeMachine {
|
|||
}
|
||||
|
||||
set waterAmount(value) {
|
||||
if (value < 0) throw new Error("Negative water");
|
||||
if (value < 0) value = 0;
|
||||
this.#waterAmount = value;
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue