JS扩展构造函数类

时间:2016-08-22 07:17:39

标签: javascript class extends

我正在学习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; +}时,我不知道如何做一个新的构造函数我得到了一个错误:(

谢谢;)!

1 个答案:

答案 0 :(得分:1)

如果要扩展课程并定义构造函数,如果要使用super(),则需要调用this

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

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

相关问题