关于ES6类中getter/setter映射waterAmount与_waterAmount的技术咨询
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:
waterAmountisn't a regular instance property
The class doesn't define a literalwaterAmountproperty on its instances. Instead,set waterAmount(value)andget waterAmount()are special "accessor methods" attached to the class's prototype. They act as controlled gateways to the internal_waterAmountproperty that actually holds the data.Assignment automatically triggers the setter
When you writecoffeeMachine.waterAmount = -10, JavaScript doesn't try to assign to a directwaterAmountproperty on the instance. Instead, it checks if there's asetmethod forwaterAmounton the instance's prototype (which there is in your class). It then runs that setter method, passing-10as thevalueparameter.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 theError: Negative watermessage here. If the value was valid, it would assign the value tothis._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.Reading
waterAmountfollows the same logic
If you later wroteconsole.log(coffeeMachine.waterAmount), JavaScript would automatically call theget waterAmount()method, which simply returns the value stored inthis._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

