无法在 es6 继承的类中设置属性

Unable to set property in es6 inherited class

本文关键字:设置 属性 继承 es6      更新时间:2023-09-26

我的基类在这里:游戏对象

class GameObject { // Represents any interactable object within the game, be it the snake or the food or the snake world itself
  constructor(x = 0, y = 0, width = 0, height = 0) {
    this._x = x;
    this._y = y;
    this._width = width;
    this._height = height;
  }
  get x() {
    return this._x;
  }
  set x(x) {
    this._x = x;
  }
  get y() {
    return this._y;
  }
  set y(y) {
    this._y = y;
  }
  get position() {
    return {
      x: this._x,
      y: this._y
    }
  }
  set position(pos) {
    this._x = pos.x;
    this._y = pos.y;
  }
  get width() {
    return this._width;
  }
  set width(width) {
    this._width = width;
  }
  get height() {
    return this._height;
  }
  set height(height) {
    this._height = height;
  }
  get dimensions() {
    return {
      width: this._width,
      height: this._height
    }
  }
  set dimensions(dimensions) {
    this._width = dimensions.width;
    this._height = dimensions.height;
  }
}

我的孩子班在这里:儿童班

class Snake extends GameObject {
  constructor() {
    super.dimensions = {width: 3};
  }
}

问题是当 Babel 运行这段代码时,它不会在最终的 JS 输出中生成构造函数方法。我只是想在蛇类构造函数中设置蛇的宽度。我希望宽度由父类定义。

试试这个:

class Snake extends GameObject {
  constructor(...args) {
    super(...args);
    this.dimensions = {width: 3};
  }
}