受保护的属性和方法
class CoffeeMachine {
_waterAmount = 0;
set waterAmount(value) {
if (value < 0) throw new Error("Negative water");
this._waterAmount = value;
}
get waterAmount() {
return this._waterAmount;
}
constructor(power) {
this._power = power;
}
}
let coffeeMachine = new CoffeeMachine(100);
coffeeMachine.waterAmount = -10;
class CoffeeMachine {
constructor(power) {
this._power = power;
}
get power() {
return this._power;
}
}
let coffeeMachine = new CoffeeMachine(100);
alert(`Power is: ${coffeeMachine.power}W`);
coffeeMachine.power = 25;
class CoffeeMachine {
_waterAmount = 0;
setWaterAmount(value) {
if (value < 0) throw new Error("Negative water");
this._waterAmount = value;
}
getWaterAmount() {
return this._waterAmount;
}
}
new CoffeeMachine().setWaterAmount(100);
- 受保护的字段是可以被继承的
如果我们继承 class MegaMachine extends CoffeeMachine
,那么什么都无法阻止我们从新的类中的方法访问 this._waterAmount
或 this._power
。
私有的属性和方法
- 私有属性和方法应该以 # 开头。它们只在类的内部可被访问
class CoffeeMachine {
#waterLimit = 200;
#checkWater(value) {
if (value < 0) throw new Error("Negative water");
if (value > this.#waterLimit) throw new Error("Too much water");
}
}
let coffeeMachine = new CoffeeMachine();
coffeeMachine.#checkWater();
coffeeMachine.#waterLimit = 1000;
- 私有字段和公有字段不会发生冲突。我们可以同时拥有私有的
#waterAmount
和公共的 waterAmount
字段。
<!DOCTYPE html>
<script>
"use strict";globalThis.__codeBoxId = "1ewehyfllh";
class CoffeeMachine {
#waterAmount = 0;
get waterAmount() {
return this.#waterAmount;
}
set waterAmount(value) {
if (value < 0) throw new Error("Negative water");
this.#waterAmount = value;
}
}
let machine = new CoffeeMachine();
machine.waterAmount = 100;
alert(machine.waterAmount);
alert(machine.#waterAmount);
</script>
- 但是如果我们继承自
CoffeeMachine
,那么我们将无法直接访问 #waterAmount
。我们需要依靠 waterAmount getter/setter
class MegaCoffeeMachine extends CoffeeMachine {
method() {
alert( this.#waterAmount );
}
}