Javascript JS扩展构造函数类

Javascript JS扩展构造函数类,javascript,class,extends,Javascript,Class,Extends,我在学习JS,我创建了一个类实体,如下所示: 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; t

我在学习JS,我创建了一个类
实体
,如下所示:

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();
    }
}
类实体{
构造函数(x=0,y=0,dx=0,dy=0,宽度=50,高度=50,实心=false,
color=“black”,name=“entity”,id=Math.random(){
这个.x=x;
这个。y=y;
this.dx=dx;
this.dy=dy;
这个。宽度=宽度;
高度=高度;
这个。固体=固体;
这个颜色=颜色;
this.name=名称;
this.id=id;
entityList[id]=此;
}
更新位置(){
this.x+=this.dx;
this.y+=this.dy;
}
画(){
ctx.save();
ctx.fillStyle=this.color;
ctx.fillRect(this.x,this.y,this.width,this.height);
ctx.restore();
}
边界碰撞(){
如果(this.solid==true){
if(this.x=canvas.width){
this.dx=-this.dx;
}
if(this.y=canvas.height){
this.dy=-this.dy;
}
}
}
EntityUpdate(){
this.UpdatePosition();
这个.Draw();
这个.BorderCollision();
}
}
现在,我想在一个名为
Player
的新类中扩展这个类,它有一个新成员:
canMove

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


谢谢

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

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

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

这里有一个很好的解释-谢谢,我这样做了:lass Player扩展了实体{constructor(canMove){super.constructor();this.canMove=canMove;}}}我得到了一个新错误:“未捕获引用错误:这不是定义的player@index.html:84(匿名函数)@index.html:145”再次感谢您的帮助;)@AlexandreDaubricourt
超级构造函数
???它需要是
super()
id=Math.random()
entityList[id]=this(在构造函数中)看起来像是坏主意。