JavaScript - '这个'在setTimeout和requestAnimationFrame中

时间:2014-11-25 20:28:43

标签: javascript animation requestanimationframe

我的问题与以下内容有关:

setTimeout() inside JavaScript Class using “this”

calling a function inside setTimeout and inside a function

我试图实现一个简单的动画循环。绘图函数是状态对象的成员函数。我在遇到这个问题时遇到了问题。在setTimeout和requestAnimationFrame中工作。

我有以下代码:

ANIM.State.prototype = {
    constructor: ANIM.State,
    play: function(){
        if(!this.paused){
            var that = this;
            setTimeout(function(){
                requestAnimationFrame(that.play);
                that.setFrameNum(that.currentFrame + 1); //draw code is in here
            }, 1000 / 24);
        }
    }
};

然而,当我调用play()时,它会运行两次并停止。

有更好的方法吗?如果可能的话,我真的希望将此功能保留为类功能,而不是全局功能。

1 个答案:

答案 0 :(得分:2)

您可以使用.bind()解决您的问题:

requestAnimationFrame(that.play.bind(that));

问题是传递给requestAnimationFrame()的所有内容都是对.play方法的引用,然后它作为普通函数调用执行,因此this内的obj.method()将是错误的并且将会不指向你的对象。将方法作为回调传递到您希望将其作为.bind()调用时,这是一个常见问题。

有许多可能的解决方法,但现代浏览器中最简单的方法是使用that.play(),如上所示。这实际上创建了一个小的存根函数,然后调用play()而不仅仅是requestAnimationFrame(),以便根据需要使用对象引用,并且它是传递给.bind()的存根函数。

你也可以这样做(创建你自己的存根函数),虽然requestAnimationFrame(function() { that.play(); }); 对我来说似乎更清晰:

{{1}}
相关问题