js中class继承时getter和setter的小坑

89 阅读1分钟

问题重现:

  • A类中设计了 width 和 height 的 getter 和 setter
  • B类继承A类
  • B类复写 width 和 height 的 setter 方法
  • 当实例化 B 类的时候,width和height变成了undefined
class A {
  _width = 0
  _height = 0

  get width() {
    return this._width
  }
  set width(value) {
    this._width = value
  }

  get height() {
    return this._height
  }
  set height(value) {
    this._height = value
  }

  constructor(width, height) {
    this._width = width
    this._height = height
  }
}

class B extends A {
  set width(value) {
    this._width = value
  }
  set height(value) {
    this._height = value
  }

  constructor(width, height) {
    super(width, height)
  }
}

const a = new A(3, 4)
const b = new B(5, 6)
console.log(a.width, a.height)  //输出3,4
console.log(b.width, b.height)  //输出undefined,undefined

原因:

暂时没有时间深入分析,可能是在子类设置setter会使父类的getter失效

解决方式:

在子类把getter方法也重写一下就行了。

class A {
  _width = 0
  _height = 0

  get width() {
    return this._width
  }
  set width(value) {
    this._width = value
  }

  get height() {
    return this._height
  }
  set height(value) {
    this._height = value
  }

  constructor(width, height) {
    this._width = width
    this._height = height
  }
}

class B extends A {
  set width(value) {
    this._width = value
  }
  set height(value) {
    this._height = value
  }
  get width() {
    return this._width
  }
  get height() {
    return this._height
  }

  constructor(width, height) {
    super(width, height)
  }
}

const a = new A(3, 4)
const b = new B(5, 6)
console.log(a.width, a.height)  //输出3,4
console.log(b.width, b.height)  //输出5,6