首页 > 解决方案 > 如何创建一个新类,我的两个类都将从中继承方法和属性?

问题描述

我有两个班级,一个叫做“玩家”,另一个叫做“敌人”。它们都具有相似的方法和属性,我希望它们从我将创建并称为“游戏对象”的父类继承。

我该如何去创造它?

这段代码是用 Javascript 编写的,我自己尝试过研究,但没能很好地理解它。

class Enemy
{
    constructor(sprite, positionX, positionY, speed)
    {
        this.sprite = sprite;
        this.positionX = positionX;
        this.positionY = positionY;
        this.speed = speed;
        this.direction = Math.floor(Math.random()*7) + 1;
        this.direction *= Math.floor(Math.random()*2) == 1 ? 1 : -1;
        this.active = false;
    }
    getCenterPoint()
    {
        return new Point(this.positionX + 16, this.positionY + 16);
    }
}

class Player
{
    constructor(sprite, positionX, positionY, speed)
    {
        this.sprite = sprite;
        this.positionX = positionX;
        this.positionY = positionY;
        this.speed = speed;
        this.animationFrame = true;
    }
        getCenterPoint()
    {
        return new Point(this.positionX + 16, this.positionY + 16);
    }
}   

我无法获得我想要的结果,需要一些指导。

标签: javascriptclassecmascript-6es6-class

解决方案


您可以extends在 ES6 类中使用关键字进行继承:

class GameObject {
  constructor(sprite, positionX, positionY, speed) {
    this.sprite = sprite;
    this.positionX = positionX;
    this.positionY = positionY;
    this.speed = speed;
  }
  getCenterPoint() {
    return new Point(this.positionX + 16, this.positionY + 16);
  }
}

class Enemy extends GameObject {
  constructor(...props) {
    super(...props);
    this.direction = Math.floor(Math.random() * 7) + 1;
    this.direction *= Math.floor(Math.random() * 2) == 1 ? 1 : -1;
    this.active = false;
  }
}

class Player extends GameObject {
  constructor(...props) {
    super(...props);
    this.animationFrame = true;
  }
}

推荐阅读