2016-08-22 139 views
2

我學習JS,我創建了一個類Entity這樣的: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(); 
    } 
} 

而現在,我要擴展這個類中新建一個名爲Player誰擁有了新的成員:canMove

但我不知道該怎麼做一個新的構造原因,當我寫constructor(canMove) {this.canMove = canMove; +}我得到一個錯誤:(

謝謝)!

+0

這裏是一個很好的解釋 - https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Classes – Pugazh

+0

謝謝,我這樣做: 姑娘播放器擴展實體 { \t構造(canMove) \t { \t \t super.constructor(); \t \t this.canMove = canMove; \t}} ,我得到了一個新的錯誤: 「未捕獲的ReferenceError:這是不是definedPlayer @的index.html:84(匿名函數)@ index.html的:145」 再次 感謝您幫助我;) –

+0

@ AlexandreDaubricourt'super.constructor' ???它需要是'super()' – Bergi

回答

1

如果要擴展一個類,定義構造函數,你需要調用super()如果你想使用this

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

你可能也會想一些參數傳遞給super,因爲你很難想要複製整個參數列表,您可能需要使用options object而不是10個單獨的參數。