Javascript requestAnimationFrame仅在不使用类的情况下工作,如何修复它?

Javascript requestAnimationFrame仅在不使用类的情况下工作,如何修复它?,javascript,html5-canvas,babeljs,Javascript,Html5 Canvas,Babeljs,我正在尝试学习javascript和canvas的动画和简单游戏,我已经编写了两个版本的测试游戏,先是函数编程,然后是对象(使用babel),它们都有相同的动画更新原始代码,但只有第一个版本可以在浏览器中工作,oop版本,给了我错误: ReferenceError: update is not defined 我应该如何管理requestAnimationFrame上的更新 我尝试将变量更改为this.update或this.update(),但结果相同 功能性: var c = docum

我正在尝试学习javascript和canvas的动画和简单游戏,我已经编写了两个版本的测试游戏,先是函数编程,然后是对象(使用babel),它们都有相同的动画更新原始代码,但只有第一个版本可以在浏览器中工作,oop版本,给了我错误:

ReferenceError: update is not defined
我应该如何管理requestAnimationFrame上的更新

我尝试将变量更改为this.update或this.update(),但结果相同

功能性:


var c = document.getElementById("game");
var ctx = c.getContext("2d");
c.width = window.innerWidth/2;
c.height = window.innerHeight/2;
ctx.scale(20,20);
var player = {
  pos: { x:0, y:0 },
  vel: 2

};

var keys = {
  left:37, up:38, right: 39, down:40
};



function update() {
  ctx.clearRect(0, 0, c.width, c.height);
  draw();
  requestAnimationFrame(update);
}

function draw() {
  ctx.fillRect(player.pos.x, player.pos.y, 1, 1);
  //ctx.clearRect(0, 0, c.width, c.height);
}

function keyboardHandler(event) {
  switch(event.keyCode) {
      case keys.left:
        player.pos.x -= 1*player.vel;
        console.log(player.pos.x);
        break;
      case keys.up:
        player.pos.y -= 1*player.vel;
        console.log(player.pos.y);
        break;
      case keys.right:
        player.pos.x += 1*player.vel;
        console.log(player.pos.x);
        break;
      case keys.down:
        player.pos.y += 1*player.vel;
        console.log(player.pos.y);
        break;
  } // switch
} // keyboardhandler

document.addEventListener('keydown', keyboardHandler, false);
update();

对象(巴别塔):

你必须:1)你的方法来
这个
或者,2)使用

第一种选择:

...
update() {
    this.ctx.clearRect(0, 0, this.c.width, this.c.height);
    this.draw();
    requestAnimationFrame(this.update.bind(this));
}
第二种选择:

...
update = () => {
    this.ctx.clearRect(0, 0, this.c.width, this.c.height);
    this.draw();
    requestAnimationFrame(this.update);
}

你必须选择你的方法来
这个
或者使用箭头函数。@K3nzie如果我的答案解决了你的问题,你也可以投票给我
...
update = () => {
    this.ctx.clearRect(0, 0, this.c.width, this.c.height);
    this.draw();
    requestAnimationFrame(this.update);
}