【问题标题】:JavaScript - 'this' inside setTimeout and requestAnimationFrameJavaScript - setTimeout 和 requestAnimationFrame 中的“this”
【发布时间】:2015-01-24 00:13:26
【问题描述】:

我的问题与以下有关:

setTimeout() inside JavaScript Class using “this”

calling a function inside setTimeout and inside a function

我正在尝试实现一个简单的动画循环。 draw 函数是状态对象的成员函数。我在让“this”在 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() 时,它会运行两次并停止。

有没有更好的方法来做到这一点?如果可能的话,我真的很想将此函数保留为类函数,而不是全局函数。

【问题讨论】:

    标签: javascript animation requestanimationframe


    【解决方案1】:

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

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

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

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

    你也可以这样做(创建你自己的存根函数),尽管.bind() 对我来说似乎更干净:

    requestAnimationFrame(function() {
        that.play();
    });
    

    【讨论】:

      猜你喜欢
      • 2017-03-23
      • 2011-08-20
      • 2021-10-13
      • 2020-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-07
      相关资源
      最近更新 更多