在requestAnimationFrame中设置正确的this-value

时间:2013-05-14 22:54:14

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

然后当我这样做时:

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

我明白了:

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

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

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

2 个答案:

答案 0 :(得分: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. 
        ]
    };
}

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

答案 1 :(得分:1)

您需要缓存对this的引用:

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

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