2

I'm learning JS, i created a class Entity like this :

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

And now, i want to extend this class in a new one called Player who have a new member : canMove

But i don't know how to do a new constructor cause when i write constructor(canMove) {this.canMove = canMove; +} i got an error :(

thanks ;) !

Andy Jazz
  • 49,178
  • 17
  • 136
  • 220
Alexandre Daubricourt
  • 3,323
  • 1
  • 34
  • 33
  • Here is a good explanation - https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Classes – Pugazh Aug 22 '16 at 07:21
  • Thanks, i did that : lass Player extends Entity { constructor(canMove) { super.constructor(); this.canMove = canMove; } } And i got a new error : "Uncaught ReferenceError: this is not definedPlayer @ index.html:84(anonymous function) @ index.html:145" Thanks again for helping me ;) – Alexandre Daubricourt Aug 22 '16 at 08:41
  • @AlexandreDaubricourt `super.constructor`??? It needs to be `super()` – Bergi Sep 15 '16 at 18:27
  • `id=Math.random()` and `entityList[id] = this;` (inside a constructor) look like bad ideas. – Bergi Sep 15 '16 at 18:33

1 Answers1

1

If you are extending a class and define a constructor, you need to call super() if you want to use this:

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

You probably will also want to pass some arguments to super, and since you hardly want to duplicate the entire arguments list you probably will want to use an options object instead of 10 separate parameters.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375