Internal and external interface
// 創造咖啡機
// waterAmount & power 都可以從外部得到
class CoffeeMachine {
waterAmount = 0; // the amount of water inside
constructor(power) {
this.power = power;
alert( `Created a coffee-machine, power: ${power}` );
}
}
// create the coffee machine
let coffeeMachine = new CoffeeMachine(100);
// add water
coffeeMachine.waterAmount = 200;
// 內部屬性通常會使用 _ 作區別
// 增加對 waterAmount 的控制
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;
}
}
// create the coffee machine
let coffeeMachine = new CoffeeMachine(100);
// add water
coffeeMachine.waterAmount = -10; // Error: Negative water
// power 只能在創在物件時設定,之後不能更改
class CoffeeMachine {
// ...
constructor(power) {
this._power = power;
}
get power() {
return this._power;
}
}
// create the coffee machine
let coffeeMachine = new CoffeeMachine(100);
alert(`Power is: ${coffeeMachine.power}W`); // Power is: 100W
coffeeMachine.power = 25; // Error (no setter)
// class MegaMachine extends CoffeeMachine,MegaMachine 可以取得
// this._waterAmount & this._power,protected fields 會被繼承
// 新增的準則,引擎還沒支援
// # 會把屬性變為私有,不能從外部或繼承取得
class CoffeeMachine {
#waterLimit = 200;
#checkWater(value) {
if (value < 0) throw new Error("Negative water");
if (value > this.#waterLimit) throw new Error("Too much water");
}
_waterAmount = 0;
set waterAmount(value) {
this.#checkWater(value);
this._waterAmount = value;
}
get waterAmount() {
return this._waterAmount;
}
}
let coffeeMachine = new CoffeeMachine();
coffeeMachine.#checkWater(); // Error
coffeeMachine.#waterLimit = 1000; // Error
coffeeMachine.waterAmount = 100; // Works
// waterAmount 變成 #waterAmount 的訪問函數
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); // Error