Is it possible to call a super setter in ES6 inherited classes?

北城以北 提交于 2019-11-29 16:42:47

问题


I'm wondering if the following is in compliance with the ES6 spec:

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";
  }
}

The idea is that let y = new Y(""); y.name = "hi" should result in y.name === "hiXY" being true.

As far as I can tell, this doesn't work in Chrome with the ES6 flag turned on. It also doesn't work using Babel with the es2015 flag. Is using super.name = ... in an inherited setter not part of the ES6 spec? Or is this a bug in the implementation of Babel?


回答1:


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

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

will override the name properly with an accessor for just the setter, with no getter. That means your y.name === "hiXY" will fail because y.name will return undefined because there is no getter for name. You need:

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

  get name(){
    return super.name;
  }

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



回答2:


for this case you have a more simple solution:


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


来源:https://stackoverflow.com/questions/34456194/is-it-possible-to-call-a-super-setter-in-es6-inherited-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!