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?

有帮助吗?

解决方案

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.

其他提示

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 **
        ...
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top