子类变量是未定义的-js



我正在编程一个游戏,在变量和继承方面遇到了问题,每当我试图在继承的类中访问它们时,它们都会显示为undefined。我曾尝试使用super来帮助解决这个问题,但没有成功,这可能是因为我对JavaScript相对陌生。

变量在基类中工作,但在子类中不工作。这是继承的类这是基类。

只是为了澄清我要问的问题,为什么变量在子类中出现未定义,而在基类中没有,以及我如何解决这个问题。谢谢

代码在图片中更清晰。

class charachter {
constructor(xPos, yPos) {
this.rightVelocity = 0;
this.leftVelocity = 0;
this.upVelocity = 0;
this.downVelocity = 0;
this.xyCordsRaw = [xPos, yPos];
this.xyCordsBlock = [Math.round(this.xyCordsRaw[0] / 50),
Math.round(this.xyCordsRaw[1] / 100)
]
}
updateCharachter() {
ctx.drawImage(charachterRight, this.xyCordsRaw[0],
this.xyCordsRaw[1])
}
findTileStandingOnType() {
return
solidObjects.includes(biome[this.xyCordsBlock[1] + 1][this.xyCordsBlock[0]])
}
isOnTheGround() {
return this.findTileStandingOnType() == true &&
this.xyCordsRaw[1] == (this.xyCordsBlock[1] * 100) + 25
}
isTileAbove() {
return solidObjects.includes(biome[this.xyCordsBlock[1] - 1]
[this.xyCordsBlock[0]])
}
isTouchingTileAbove() {
return this.isTileAbove() == true && this.xyCordsBlock[1] * 100 == this.xyCordsRaw[1]
}
isWallLeft() {
return solidObjects.includes(biome[this.xyCordsBlock[1]][this.xyCordsBlock[0] - 1])
}
isWallRight() {
return solidObjects.includes(biome[this.xyCordsBlock[1]][this.xyCordsBlock[0] + 1])
}
isTouchingWallRight() {
return this.isWallRight() == true && this.xyCordsBlock[0] * 50 == this.xyCordsRaw[0]
}
isTouchingWallLeft() {
return this.isWallLeft() == true && this.xyCordsBlock[0] * 50 == this.xyCordsRaw[0]
}
}
class playerChar extends charachter {
constructor(xPos, yPos, leftVelocity, rightVelocity, upVelocity, downVelocity, xyCordsRaw, xyCordsBlock) {
super(xPos, yPos, leftVelocity, rightVelocity, upVelocity, downVelocity, xyCordsRaw, xyCordsBlock);
document.addEventListener('keydown', this.takeInput);
}
takeInput(e) {
if (e.code == 'KeyA') {
console.log(this.leftVelocity);
}
if (e.code == 'KeyW') {
console.log("The letter W was pressed");
}
if (e.code == 'KeyD') {
console.log(this.xyCordsRaw);
}
}
}
var player = new playerChar(150, 325);

当前的问题是在事件侦听器中使用this

document.addEventListener('keydown', this.takeInput);

在调用addEventListener时传递对takeInput函数对象的引用,并且因为它是document的事件处理程序,所以takeInput在被调用时将具有documentthis值。尝试

document.addEventListener('keydown', this.takeInput.bind(this));

首先看看它有什么不同。


下一个要纠正的错误是中return之后的换行

findTileStandingOnType(){
return 
solidObjects.includes(biome[this.xyCordsBlock[1]

这应该是

findTileStandingOnType(){
return solidObjects.includes(biome[this.xyCordsBlock[1] + 1][this.xyCordsBlock[0]])}

不带分号分隔符的返回语句只有在出现语法错误时才在下一行继续。这不是案例在这里。

最新更新