这个问题已经在这里有一个答案:
我试图做一个简单的游戏(移动块现在)我自己。我的一个类功能,即更新游戏方面有一个方法,update()
,调用到同一类,displBackground()
和displCharacters()
的其他方法。当我看到我的浏览器控制台,我看到以下消息:类型错误:this.displBackground不是一个函数
我已经看到过: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Not_a_function Not able to call method within another method of the same class JS (和其他一些人,其中包括相当长的一段做题,我的时间不多了,所以我会在稍后一一列举了)我还没有尝试从类声明的对象,而不是直接的,但我会保存为最后的手段。
const gameContext = class {
constructor() {
this.c = document.getElementById("game");
this.ctx = this.c.getContext("2d");
this.characters = [];
this.interval = setInterval(this.update, 20);
};
addCharacter(char) {
this.characters.push(char)
}
displBackground() {
this.ctx.fillStyle = '#eeeeff';
this.ctx.fillRect(0, 0, this.c.width, this.c.height);
}
displCharacters() {
if (this.characters == 0) return
for (var i = 0; i < this.characters.length; i++) {
var character = this.characters[i];
this.ctx.fillStyle = character.color;
this.ctx.fillRect((character.pos[0]-character.size),
(character.pos[1]-character.size),
(character.pos[0]+character.size),
(character.pos[1]+character.size));
}
}
update() {
this.displBackground();
this.displCharacters();
console.log(KEYMAP); // This is a function that tells me what keys are currently pressed, and works well isolated.
}
}
我想看看画布更新第二50次随着时间的推移,后来就确保该块可以移动(displBackground绘制背景,而dsplCharacters绘制的人物,在上面)
绑定在你的构造方法,你是好去。
constructor() {
this.c = document.getElementById("game");
this.ctx = this.c.getContext("2d");
this.characters = [];
this.interval = setInterval(this.update, 20);
this.update = this.update.bind(this);
this.displBackground = this.displBackground.bind(this);
this.displCharacters = this.displCharacters.bind(this);
};
正在发生的事情是,
this.interval = setInterval(this.update, 20);
没有约束力this
到this.update
功能。
另一种方式来解决这个问题是:
constructor() {
this.c = document.getElementById("game");
this.ctx = this.c.getContext("2d");
this.characters = [];
this.interval = setInterval( ()=> this.update(), 20);
};