繁体   English   中英

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

[英]Unable to set property in es6 inherited class

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM