使用此关键字的requestAnimationFrame [英] requestAnimationFrame with this keyword
问题描述
我正在使用 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屋!