我如何创建一个新的 class,我的两个 class 都会从中继承方法和属性?
How do I create a new class which both of my classes will inherit methods and properties from?
我有两个class,一个叫"Player",一个叫"Enemy"。它们都有相似的方法和属性,我希望它们从父 class 继承,我将创建并调用 "Game Object".
我该如何创建它?
这段代码是在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);
}
}
我无法获得想要的结果,需要一些指导。
在ES6中可以使用extends
关键字进行继承类:
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;
}
}
我有两个class,一个叫"Player",一个叫"Enemy"。它们都有相似的方法和属性,我希望它们从父 class 继承,我将创建并调用 "Game Object".
我该如何创建它?
这段代码是在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);
}
}
我无法获得想要的结果,需要一些指导。
在ES6中可以使用extends
关键字进行继承类:
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;
}
}