使用 requestAnimationFrame 的 JS 游戏循环 - 对象函数只调用一次
JS game loop using requestAnimationFrame - object functions are called only once
对不起,我是js的菜鸟,以为我已经掌握了对象实例和函数的基础知识,结果我没有也不知道如何弄清楚该怎么做。
我已经声明了一个像这样的 GameLoop 函数/对象:
function GameLoop() {
window.requestAnimationFrame =
window.requestAnimationFrame || /* Firefox 23 / IE 10 / Chrome */
window.mozRequestAnimationFrame || /* Firefox < 23 */
window.webkitRequestAnimationFrame || /* Safari */
window.msRequestAnimationFrame || /* IE */
window.oRequestAnimationFrame; /* Opera */
this.start = function() {
this.update();
};
this.update = function() {
this.processInput();
this.updateState();
this.updateGraphics();
window.requestAnimationFrame(this.update);
};
this.processInput = function() {
alert("pi");
};
this.updateState = function() {
alert("us");
};
this.updateGraphics = function() {
alert("ug");
};
};
我正在尝试像这样运行它:
$(document).ready(main);
function main() {
var gameLoop = new GameLoop();
gameLoop.start();
}
发生的事情是,每个"processInput"updateStaten"和"updateGraphics"函数都被调用一次(我可以看到它们显示的每个警报),但随后它停止并且我得到的错误(在Firefox的错误控制台中)是
Error: TypeError: this.processInput is not a function
指向update
函数内的this.processInput()
行。
我只是不明白为什么,特别是因为第一次调用函数。谁能帮忙?
您的函数以错误的this
运行。
this
是根据您调用函数的方式设置的。
当被requestAnimationFrame
调用时,this
将被window
。
要解决此问题,您需要在闭包中保留this
:
var self = this;
requestAnimationFrame(function() { self.processInput(); });
您还可以使用新的 ES5 bind()
函数为您执行此操作:
requestAnimationFrame(this.processInput.bind(this));
相关文章:
- 如何在chrome扩展中存储数据/结果,以及如何使用setTimeout使其只被调用一次
- Rails操作只调用一次,但我在ajax中每秒钟都调用一次
- Angular 1.5变量在调用一次之前不起作用
- 如何每 10 秒调用一次 JS 函数,然后以角度激活一个函数
- Javascript 计时器只调用一次 Code 隐藏方法
- 一段时间后调用函数,但只调用一次
- 每隔1秒调用一次jQueryajax是否安全
- 什么时候函数只能调用一次
- 如何在重复满足条件时调用一次辅助函数
- JS:.apply(null,arguments)——为什么我的函数被调用一次,而console.log被调用多次
- Angular指令删除只调用一次的DOM元素
- 对于新建的元素,onchange函数只调用一次
- ASP.NET:每5分钟从代码后面调用一次弹出窗口
- 每10秒调用一次页面加载事件
- 调用一次jQuery函数
- 我想在窗口加载后只调用一次JavaScript setInterval函数
- 如何只调用一次事件处理程序,而不是每次单击项目时调用事件处理程序
- 回调函数不会在使用 $timeout 的服务中只调用一次
- Angular 1.5.0 - 为什么工厂只调用一次
- 仅调用一次 onkeyup 函数