【问题标题】:Do i really need to use a setter/getter with javascript ES6 Class? [duplicate]我真的需要使用带有 javascript ES6 类的 setter/getter 吗? [复制]
【发布时间】:2016-03-13 12:39:48
【问题描述】:

我在玩 ES6 Class,我想知道使用 getset 方法来处理该类的属性有什么意义。它们似乎毫无意义,因为无论如何你都可以在类上设置任意属性。

例如这个类

class Group {

  constructor() {}

  set name(newName) {
    this._name = newName;
  }

  get name() {
    return this._name;
  }

  print() {
    console.log('this._name = ', this._name);
    console.log('this.name = ', this.name);
  }
}

我得到了这些结果

var group = new Group();
group._name = 'foo';
console.log('_name = ', group._name); => _name = foo
console.log('name = ', group.name); => name = foo
group.print(); => this._name = foo
               => this.name = foo

var group2 = new Group();
group2.name = 'bar';
console.log('_name = ', group2._name); => _name = bar
console.log('name = ', group2.name); => name = bar
group2.print(); => this._name = bar
                => this.name = bar

从这个例子的结果来看,似乎通过使用新的setget 方法只会给我的类增加不必要的膨胀。

【问题讨论】:

  • 当您想在获取和设置值之前操作/修改值时,这些方法很有用,如果您不想这样做,则不需要它们。
  • 如果你的 getter 和 setter 只是读/写另一个属性而不做其他事情,那么它们确实是不必要的。

标签: javascript ecmascript-6


【解决方案1】:

使用属性访问器允许您运行其他代码,例如,检查值是否有效:

set name(newName) {
  if (newName === '')
      throw new Error("Name cannot be empty");
  this._name = newName;
}

或计算复杂的属性:

get fullname() {
    return this.firstName + ' ' + this.lastName;
}

【讨论】:

  • 我可以看到您的 set 示例,但在您的 get 示例中,您不能取消 get 并只使用 fullname()... 吗?
  • 你可以这样做,但它是一个方法调用而不是一个属性。我经常在 .NET 中工作 - 有时拥有属性而不是方法非常有用。
  • 哦,使用get 你可以只使用myGroup.fullname 而不是myGroup.fullname()
猜你喜欢
  • 1970-01-01
  • 2017-01-28
  • 2020-03-17
  • 2017-07-07
  • 2016-07-01
  • 1970-01-01
  • 2016-02-22
  • 1970-01-01
  • 2019-05-04
相关资源
最近更新 更多