带有此关键字的 requestAnimationFrame [英] requestAnimationFrame with this keyword

查看:26
本文介绍了带有此关键字的 requestAnimationFrame的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 webkitRequestAnimationFrame 但我在对象内部使用它时遇到问题.如果我传递 this 关键字,它将使用 window 并且我找不到一种方法来代替它使用指定的对象.

I'm using webkitRequestAnimationFrame but I'm having trouble using it inside of an object. If I pass the this keyword it will use window and I can't find a way for it to use the specified object instead.

示例:

Display.prototype.draw = function(){
  this.cxt.clearRect(0, 0, this.canvas.width, this.canvas.height);
  //Animation stuff here.

  window.webkitRequestAnimationFrame(this.draw);
};

我也试过这个,但无济于事:

I have also tried this but to no avail:

Display.prototype.draw = function(){
  this.cxt.clearRect(0, 0, this.canvas.width, this.canvas.height);
  //Animation stuff here.

  var draw = this.draw;
  window.webkitRequestAnimationFrame(draw);
};

推荐答案

我正在尝试传递 display.draw,它是 webkitRequestAnimationFram 所在的函数.

I'm trying to pass display.draw which is the function in which webkitRequestAnimationFram resides.

webkitRequestAnimationFrame 大概会调用您传入的函数,如下所示:

webkitRequestAnimationFrame will presumably call the function you pass in, something like this:

function webkitRequestAnimationFrame(callback)
{
    // stuff...
    callback();
    // other stuff...
}

此时,您已将 draw 函数与其调用上下文分离(分离).您需要将函数(draw)绑定到它的上下文(Display 的实例).

At this point, you have dissociated (detached) the draw function from its invocation context. You need to bind the function (draw) to its context (the instance of Display).

您可以使用 Function.bind,但这需要 JavaScript 1.8 支持(或者只使用推荐的补丁).

You can use Function.bind, but this requires JavaScript 1.8 support (or just use the recommended patch).

Display.prototype.draw = function()
{
    // snip...

    window.webkitRequestAnimationFrame(this.draw.bind(this));
};

这篇关于带有此关键字的 requestAnimationFrame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆