在requestAnimationFrame中设置正确的this-value

acr*_*uui 2 javascript html5-canvas requestanimationframe

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

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. 
        ]
    };
}
Run Code Online (Sandbox Code Playgroud)

然后,当我这样做:

var theApp = app(settings);
theApp.init();
Run Code Online (Sandbox Code Playgroud)

我明白了:

Uncaught TypeError: Object [object global] has no method 'update'
Run Code Online (Sandbox Code Playgroud)

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

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

bfa*_*tto 10

您可以创建一个绑定函数(带有固定的this),并将其传递给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. 
        ]
    };
}
Run Code Online (Sandbox Code Playgroud)

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