Setting correct this-value in requestAnimationFrame

三世轮回 提交于 2019-12-06 13:41: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 **
        ...


来源:https://stackoverflow.com/questions/16554136/setting-correct-this-value-in-requestanimationframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!