2016-08-22 5 views
2

ich JS lerne, habe ich eine Klasse Entity wie folgt aus:JS Erweiterte Konstruktor Klasse

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

Und nun möchte ich diese Klasse in einer neuen Player genannt erweitern, die ein neues Mitglied haben: canMove

Aber ich weiß nicht, wie man eine neue Konstruktor Ursache tun, wenn ich constructor(canMove) {this.canMove = canMove; +} schreibe ich einen Fehler :(

dank bekam;)!

+0

Hier ist eine gute Erklärung ist - https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Classes – Pugazh

+0

Danke, ich habe das: lass Spieler Entity { \t Konstruktor (canMove) erstreckt \t { \t \t super.constructor(); \t \t this.canMove = canMove; \t} } und ich bekam einen neuen Fehler: "Nicht abgefangene Reference: Das ist nicht definedPlayer @ index.html: 84 (anonyme Funktion) @ index.html: 145" Nochmals vielen Dank für mich zu helfen;) –

+0

@ AlexandreDaulucourt 'super.constructor' ??? Es muss 'super()' sein – Bergi

Antwort

1

Wenn Sie eine Klasse erweitern und einen Konstruktor definieren, müssen Sie super() anrufen, wenn Sie verwenden möchten this:

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

Sie werden wahrscheinlich auch einige Argumente super übergeben wollen, und da Sie kaum Möchten Sie die gesamte Liste der Argumente duplizieren, verwenden Sie wahrscheinlich options object anstelle von 10 separaten Parametern.

Verwandte Themen