javascript - 如何为游戏循环进行类方法递归?
问题描述
我有这个代码:
export default class Main {
canvas: HTMLCanvasElement | null;
context: CanvasRenderingContext2D | null;
constructor() {
this.canvas = null;
this.context = null;
}
init() {
this.canvas = <HTMLCanvasElement>document.getElementById('canvas');
this.context = this.canvas.getContext('2d');
window.requestAnimationFrame(this.gameLoop);
return () => { };
}
draw() {
const randomColor = Math.random() > 0.5 ? '#ff8080' : '#0099b0';
this.context.fillStyle = randomColor;
this.context.fillRect(100, 50, 200, 175);
}
// eslint-disable-next-line no-unused-vars
gameLoop(timestamp: number) {
this.draw();
window.requestAnimationFrame(this.gameLoop);
}
core() {
window.onload = this.init();
}
}
const main = new Main();
main.core();
我收到的错误是:[Error] TypeError: undefined is not an object (evalating 'this.draw') gameLoop (main.ts:19)
但实际上,如果我this
在 gameLoop 中登录,我会明白undefined
这是有道理的,因为 gameLoop 是由 requestAnimationFrame 内部调用的,而不是由我的Main
班级调用的。并且由于同样的问题,this.draw
是未定义的。
如何解决?
解决方案
您需要将该方法绑定到您的类以确保this
指向您的类。
class Main {
canvas;
context;
init() {
this.canvas = document.getElementById('canvas');
this.context = this.canvas.getContext('2d');
window.requestAnimationFrame(this.gameLoop.bind(this));
}
draw() {
const randomColor = Math.random() > 0.5 ? '#ff8080' : '#0099b0';
this.context.fillStyle = randomColor;
this.context.fillRect(100, 50, 200, 175);
}
gameLoop(timestamp) {
this.draw();
window.requestAnimationFrame(this.gameLoop.bind(this));
}
core() {
window.onload = this.init();
}
}
const main = new Main();
main.core();
<canvas id="canvas"></canvas>
推荐阅读
- node.js - 跨子域共享 Express Session
- python - 为重复文件的输出添加大小
- dart - Dart 中这个冒号背后的原因是什么
- javascript - 如何遍历 javascript 对象中的所有子文档?
- java - 测试 1(代码强制)的运行时错误,但在 netbeans 中有效
- c# - 如何显示 Windows 窗体后面的内容?
- javascript - 两个运动物体的交集
- regex - 如何从句子中提取时间并转换为数字?
- javascript - JS 如何评估表达式 ({...}).objMethod()?
- mysql - 为什么“SELECT 'ä' = 'ae' COLLATE latin1_german2_ci;”的结果 是 1?