在requestAnimationFrame中设置正确的this-value [英] Setting correct this-value in requestAnimationFrame

查看:1986
本文介绍了在requestAnimationFrame中设置正确的this-value的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个app-object构造函数,如下所示:

I have an app-object constructer that looks like this:

var app = function(loadedsettings) {

    return {
        init: function() {          
            this.loop();
        },

        loop: function() {
            this.update();
            window.requestAnimationFrame(this.loop);
        },

        update: function() {
            //loop through settings and call update on every object.
        },

        settings: [
             //array of settings objects, all with update methods. 
        ]
    };
}

然后当我这样做时:

var theApp = app(settings);
theApp.init();

我得到:

Uncaught TypeError: Object [object global] has no method 'update'

因为当调用requestAnimationFrame时,循环函数中的this-value设置为window。

because when requestAnimationFrame is called, the this-value inside the loop function is set to window.

是否有人知道如何调用requestAnimatinFrame并将'theApp'对象设置为this -值?

Does anybody know how to call requestAnimatinFrame with the 'theApp' object set as the this-value?

推荐答案

您可以创建一个绑定函数(具有固定的) ,并将其传递给requestAnimationFrame:

You can create a bound function (with a fixed this), and pass that to requestAnimationFrame:

var app = function(loadedsettings) {

    return {
        init: function() {          
            this.loop();
        },

        loop: function() {
            this.update();
            window.requestAnimationFrame(this.loop.bind(this));
        },

        update: function() {
            //loop through settings and call update on every object.
        },

        settings: [
             //array of settings objects, all with update methods. 
        ]
    };
}

认为支持requestAnimationFrame的浏览器将会也支持Function.prototype.bind,但是遇到没有的那个,可以使用polyfill。

I think that a browser which supports requestAnimationFrame will also support Function.prototype.bind, but in case you come across one that doesn't, there are polyfills available.

这篇关于在requestAnimationFrame中设置正确的this-value的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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