Setting correct this-value in requestAnimationFram

2020-07-24 06:39发布

问题:

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. 
        ]
    };
}

Then when I do:

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

I get:

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

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

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

回答1:

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. 
        ]
    };
}

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.



回答2:

You need to cache a reference to this:

var app = function(loadedsettings) {
    var self = this;
    return {
        init: function() {          
            self.loop();
        },

        loop: function() {
            self.update();
            window.requestAnimationFrame(self.loop);
        },
        ** snip **
        ...