JS扩展构造函数类

JS Extended constructor class

本文关键字:构造函数 扩展 JS      更新时间:2023-09-26

我正在学习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; +}我得到了一个错误:(

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

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

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