【问题标题】:Is it possible to call a super setter in ES6 inherited classes?是否可以在 ES6 继承类中调用超级设置器?
【发布时间】:2016-03-31 02:23:17
【问题描述】:

我想知道以下是否符合 ES6 规范:

class X {
  constructor(name) {
    this._name = name;
  }

  get name() {
    return this._name;
  }

  set name(name) {
    this._name = name + "X";
  }
}

class Y extends X {
  constructor(name) {
    super(name);
  }

  set name(name) {
    super.name = name;
    this._name += "Y";
  }
}

这个想法是let y = new Y(""); y.name = "hi" 应该导致y.name === "hiXY" 为真。

据我所知,这在打开 ES6 标志的 Chrome 中不起作用。使用带有es2015 标志的 Babel 也不起作用。在继承的 setter 中使用 super.name = ... 不是 ES6 规范的一部分吗?或者这是 Babel 实现中的一个错误?

【问题讨论】:

  • 定义“不起作用”?您通过在没有匹配get name(){ return super.name; } 的孩子上定义set name 来覆盖基类中的get name。是这个问题吗?
  • @DenysSéguret 不,因为我希望超级的设置器运行(在名称末尾添加一个 X)。
  • @loganfsmyth 你是对的!我没有意识到定义set name 会覆盖get name。一旦我添加了吸气剂,它似乎确实有效!谢谢!

标签: javascript babeljs ecmascript-6


【解决方案1】:
class Y extends X {
  constructor(name) {
    super(name);
  }

  set name(name) {
    super.name = name;
    this._name += "Y";
  }
}

将使用 just setter 的访问器正确覆盖 name,没有 getter。这意味着您的y.name === "hiXY" 将失败,因为y.name 将返回undefined,因为name 没有getter。你需要:

class Y extends X {
  constructor(name) {
    super(name);
  }

  get name(){
    return super.name;
  }

  set name(name) {
    super.name = name;
    this._name += "Y";
  }
}

【讨论】:

  • 你刚刚为我节省了很多调试时间。
猜你喜欢
  • 2012-05-22
  • 1970-01-01
  • 1970-01-01
  • 2020-10-09
  • 1970-01-01
  • 2019-07-10
  • 2014-02-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多