繁体   English   中英

带有 getter 和 setter 方法的 ES6 类

[英]ES6 class with getter and setter methods

我正在查看使用 getter/setter 的 ES6 类示例之一;

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

我想了解以下行是如何工作的;

coffeeMachine.waterAmount = -10

我的问题是,我们在课堂内的任何地方都使用了“_waterAmount”而不是“waterAmount”

所以班级里有 3 个地方;

_waterAmount = 0; // At class level
this._waterAmount = value; // Inside set
return this._waterAmount; // Inside get

在这种情况下,它如何将 "waterAmount" 映射到 "_waterAmount" ?

_waterAmount = 0用途候选公共实例字段语法(参见为类)来定义一个自己的属性_waterAmount上由类创建的每个对象实例。

set waterAmount(value) { ... }使用set 语法(在 ES5 中引入)在类的.prototype上定义一个 setter 属性。 结果属性将存在于该类创建的实例的[[Prototype]] ( __proto__ ) 上。

get waterAmount(value) { ... }使用get 语法在类的.prototype上定义一个 getter 属性。 同样,这将存在于类创建的实例的[[Prototype]]上。

函数的目标(即“this”值)通常由它的调用方式决定。 当你写coffeeMachine.waterAmount = -10 ,该waterAmount属性上找到的[[Prototype]]coffeeMachine 该类将一个 setter 函数与此属性相关联,该属性作为 setter 正常行为的一部分被调用。

所以coffeeMachine.waterAmount = -10调用与相关联的setter函数waterAmount在属性[[Prototype]]coffeeMachine作为上的方法coffeeMachine thisthis._waterAmount = value因此是coffeeMachine ,和自己的属性_waterAmountcoffeeMachine然后具有值20分配给它。

您可以通过使用Object.getOwnPropertyDescriptors来查看该类如何配置各种属性:

 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 } } const myCoffeeMachine = new CoffeeMachine() const x = Object.getOwnPropertyDescriptors(myCoffeeMachine) const y = Object.getOwnPropertyDescriptors(myCoffeeMachine.__proto__) console.log('myCoffeeMachine: ', x) console.log('myCoffeeMachine.__proto__: ', y)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM