【问题标题】:JS Extended constructor classJS扩展构造器类
【发布时间】:2016-12-28 15:25:48
【问题描述】:

我正在学习 JS,我创建了一个类 Entity 像这样:

class Entity {

    constructor(x=0, y=0, dx=0, dy=0, width=50, height=50, solid=false,                 
                color="black", name="entity", id=Math.random()) {

    this.x = x;
    this.y = y;
    this.dx = dx;
    this.dy = dy;
    this.width = width;
    this.height = height;
    this.solid = solid;
    this.color = color;
    this.name = name;
    this.id = id;   

    entityList[id] = this;
}

UpdatePosition() {

    this.x += this.dx;
    this.y += this.dy;
}

Draw() {

    ctx.save();
    ctx.fillStyle = this.color;
    ctx.fillRect(this.x, this.y, this.width, this.height);
    ctx.restore();
}

BorderCollision() {

    if (this.solid == true) {

        if (this.x <= 0) {
            this.dx = -this.dx;
        }
            if (this.x + this.width >= canvas.width) {
                this.dx = -this.dx;
            }

            if (this.y <= 0) {
                this.dy = -this.dy;
            }

            if (this.y + this.height >= canvas.height) {
                this.dy = -this.dy;
            }
    }
}

    EntityUpdate() {

        this.UpdatePosition();
        this.Draw();
        this.BorderCollision();
    }
}

现在,我想在一个名为 Player 的新类中扩展这个类,它有一个新成员:canMove

但是我不知道如何做一个新的构造函数,因为当我写constructor(canMove) {this.canMove = canMove; +}时我得到一个错误:(

谢谢 ;) !

【问题讨论】:

  • 谢谢,我做到了: lass Player extends Entity { constructor(canMove) { super.constructor(); this.canMove = canMove;我得到了一个新错误:“Uncaught ReferenceError: this is not definedPlayer @ index.html:84(anonymous function) @ index.html:145”再次感谢您的帮助;)
  • @AlexandreDaubricourt super.constructor???必须是super()
  • id=Math.random()entityList[id] = this;(在构造函数中)看起来是个坏主意。

标签: javascript class extends


【解决方案1】:

如果你在扩展一个类并定义了一个构造函数,如果你想使用this,你需要调用super()

class Player extends Entity {
    constructor(canMove) {
        // super.constructor(); - NO
        super(); // Yes
        this.canMove = canMove;
    }
}

您可能还希望将一些参数传递给super,并且由于您不想复制整个参数列表,您可能希望使用options object 而不是10 个单独的参数。

【讨论】:

    猜你喜欢
    • 2021-12-13
    • 1970-01-01
    • 1970-01-01
    • 2013-11-15
    • 2019-01-07
    • 2021-02-13
    • 2018-08-24
    • 2014-05-29
    • 2013-05-29
    相关资源
    最近更新 更多