javascript - 如何创建一个新类,我的两个类都将从中继承方法和属性?
问题描述
我有两个班级,一个叫做“玩家”,另一个叫做“敌人”。它们都具有相似的方法和属性,我希望它们从我将创建并称为“游戏对象”的父类继承。
我该如何去创造它?
这段代码是用 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);
}
}
我无法获得我想要的结果,需要一些指导。
解决方案
您可以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;
}
}
推荐阅读
- vue.js - 如何在 vuetify 文本区域标签中使用 v-icon 而不是文本?
- javascript - 如何使用 Javascript 初始化自定义 html 类
- python - 如何检索使用从 python 脚本调用的 shell 脚本创建的文件名和文件?
- svelte - 我无法让我的 Svelte 应用程序使用“npm run dev”进行编译
- c# - 在 C# 中,如何向已构建的类添加功能?
- angular - 在角度组件计划同步融合中获得专业内的#dateHeaderTemplate
- python - 无法将字符串列表与日期时间对象进行比较
- requirements - 功能需求中的措辞
- android - SeekBar Thumb 上方的 TextView 被移动
- git - Git 子模块与 Mercurial 子存储库——显着差异?