【问题标题】:ES6 class with getter and setter methods具有 getter 和 setter 方法的 ES6 类
【发布时间】:2020-03-19 10:44:28
【问题描述】:

我正在查看使用 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 放入get & set 来定义映射。即使您在所有地方将_waterAmount 重命名为_amount,代码仍然可以工作。
  • 好的......并且是“waterAmount”或“_waterAmount”类的实际属性?
  • @testndtv 有两个属性,._waterAmount 是数据属性和(继承自原型).waterAmount 是访问器属性。 (以及在您的构造函数中定义的另一个数据属性._power
  • 谢谢....还有一件事.. For _waterAmount = 0; ,是不是和我们在constructor()里面定义一样{this._waterAmount = 0;}
  • ....意思是如果我们将其作为数据属性从外部移除,然后将其添加到构造函数中(如 _power ),那是一样的吗?

标签: javascript ecmascript-6 es6-class


【解决方案1】:

_waterAmount = 0 使用类的candidate public instance field syntax(参见also)在类创建的每个对象实例上定义自己的属性_waterAmount

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

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

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

所以coffeeMachine.waterAmount = -10 调用与coffeeMachine[[Prototype]] 上的waterAmount 属性关联的setter 函数作为coffeeMachine 上的方法。因此this._waterAmount = value 中的thiscoffeeMachine,而coffeeMachine 上的自己的属性_waterAmount 则具有分配给它的值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)

【讨论】:

    猜你喜欢
    • 2017-05-21
    • 1970-01-01
    • 2011-04-14
    • 2017-09-09
    • 2016-11-09
    • 2014-09-24
    • 2020-03-17
    • 2012-07-25
    • 2017-08-26
    相关资源
    最近更新 更多