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

后端 未结 1 707
你的背包
你的背包 2020-12-31 01:15

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

class X {
  constructor(name) {
    this._name = n         


        
相关标签:
1条回答
  • 2020-12-31 02:01
    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";
      }
    }
    
    0 讨论(0)
提交回复
热议问题