This commit is contained in:
Ilya Kantor 2020-12-05 22:30:33 +03:00
parent 6daaaa224f
commit 63d0f055fc

View file

@ -96,8 +96,9 @@ class CoffeeMachine {
_waterAmount = 0; _waterAmount = 0;
set waterAmount(value) { set waterAmount(value) {
// "throw new Error" generates an error, we'll cover it later in the tutorial if (value < 0) {
if (value < 0) throw new Error("Negative water"); value = 0;
}
this._waterAmount = value; this._waterAmount = value;
} }
@ -118,7 +119,7 @@ let coffeeMachine = new CoffeeMachine(100);
coffeeMachine.waterAmount = -10; // Error: Negative water 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" ## Read-only "power"
@ -160,7 +161,7 @@ class CoffeeMachine {
_waterAmount = 0; _waterAmount = 0;
*!*setWaterAmount(value)*/!* { *!*setWaterAmount(value)*/!* {
if (value < 0) throw new Error("Negative water"); if (value < 0) value = 0;
this._waterAmount = value; this._waterAmount = value;
} }
@ -200,19 +201,23 @@ class CoffeeMachine {
*/!* */!*
*!* *!*
#checkWater(value) { #fixWaterAmount(value) {
if (value < 0) throw new Error("Negative water"); if (value < 0) return 0;
if (value > this.#waterLimit) throw new Error("Too much water"); if (value > this.#waterLimit) return this.#waterLimit;
} }
*/!* */!*
setWaterAmount(value) {
this.#waterLimit = this.#fixWaterAmount(value);
}
} }
let coffeeMachine = new CoffeeMachine(); let coffeeMachine = new CoffeeMachine();
*!* *!*
// can't access privates from outside of the class // can't access privates from outside of the class
coffeeMachine.#checkWater(); // Error coffeeMachine.#fixWaterAmount(123); // Error
coffeeMachine.#waterLimit = 1000; // Error coffeeMachine.#waterLimit = 1000; // Error
*/!* */!*
``` ```
@ -233,7 +238,7 @@ class CoffeeMachine {
} }
set waterAmount(value) { set waterAmount(value) {
if (value < 0) throw new Error("Negative water"); if (value < 0) value = 0;
this.#waterAmount = value; this.#waterAmount = value;
} }
} }