【问题标题】:Unable to set property in es6 inherited class无法在 es6 继承类中设置属性
【发布时间】:2016-02-17 14:22:21
【问题描述】:

我的基类在这里:Game Object

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

我的孩子班在这里:Child class

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

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

【问题讨论】:

  • 请在您的问题中发布您的代码,而不是仅链接它。
  • 每个子构造函数都需要在 ES6 中调用super()。而且你不应该在super 上设置属性,而应该在this 上设置属性。
  • 你需要导出你的模块吗?所以导出 GameObject 以便您可以从它导入和扩展?
  • 如果你还没有完成模块导出,2ality.com/2014/09/es6-modules-final.html 是我最喜欢的失败之一。
  • @Bergi 啊,我明白了。我试图设置 this.width = 3,但这不起作用。还没有尝试过调用 super() 。让我检查一下!

标签: javascript ecmascript-6 babeljs


【解决方案1】:

试试这个:

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

【讨论】:

    猜你喜欢
    • 2019-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-08
    • 1970-01-01
    • 2017-10-24
    • 1970-01-01
    相关资源
    最近更新 更多