Private and protected properties and methods

Internal and external interface

物件的屬性跟方法分為 2 群

  • Internal interface – methods and properties, accessible from other methods of the class, but not from the outside.

  • External interface – methods and properties, accessible also from outside the class.

Protecting “waterAmount”

// 創造咖啡機
// 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

Read-only “power”

Private “#waterLimit”

Last updated

Was this helpful?