You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

关于ES6类中getter/setter映射waterAmount与_waterAmount的技术咨询

How does coffeeMachine.waterAmount = -10 map to _waterAmount in this ES6 class?

Question

I'm looking at this ES6 class example that uses getters and setters:

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; // Error: Negative water

I want to understand how the line coffeeMachine.waterAmount = -10 works: the class only uses _waterAmount internally and never directly uses waterAmount. How does waterAmount map to _waterAmount?


Answer

Great question—this boils down to how ES6 class accessor properties (getters and setters) work under the hood. Let's break it down clearly:

  1. waterAmount isn't a regular instance property
    The class doesn't define a literal waterAmount property on its instances. Instead, set waterAmount(value) and get waterAmount() are special "accessor methods" attached to the class's prototype. They act as controlled gateways to the internal _waterAmount property that actually holds the data.

  2. Assignment automatically triggers the setter
    When you write coffeeMachine.waterAmount = -10, JavaScript doesn't try to assign to a direct waterAmount property on the instance. Instead, it checks if there's a set method for waterAmount on the instance's prototype (which there is in your class). It then runs that setter method, passing -10 as the value parameter.

  3. The setter handles validation and maps to _waterAmount
    Inside the setter, the code first validates that the input isn't negative—this is why you get the Error: Negative water message here. If the value was valid, it would assign the value to this._waterAmount, the internal instance property that stores the actual water amount. The underscore _ is a common convention to signal this property is meant for internal use only, not direct external access.

  4. Reading waterAmount follows the same logic
    If you later wrote console.log(coffeeMachine.waterAmount), JavaScript would automatically call the get waterAmount() method, which simply returns the value stored in this._waterAmount.

In short: waterAmount is a virtual property that doesn't hold data itself. It uses the setter and getter methods to safely interact with the real data stored in _waterAmount, letting you add validation, side effects, or other logic without exposing the class's internal state directly.

内容的提问来源于stack exchange,提问作者copenndthagen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 00:07:50