【问题标题】:Setting correct this-value in requestAnimationFrame在 requestAnimationFrame 中设置正确的 this-value
【发布时间】:2013-05-14 22:54:14
【问题描述】:

我有一个 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 值吗?

【问题讨论】:

    标签: javascript html5-canvas requestanimationframe


    【解决方案1】:

    您可以创建一个绑定函数(使用固定的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。

    【讨论】:

      【解决方案2】:

      您需要缓存对this的引用:

      var app = function(loadedsettings) {
          var self = this;
          return {
              init: function() {          
                  self.loop();
              },
      
              loop: function() {
                  self.update();
                  window.requestAnimationFrame(self.loop);
              },
              ** snip **
              ...
      

      【讨论】:

      • 感谢您的回答,但是当构造函数在没有 new 运算符的情况下被调用时,我认为 this 将在分配给 self 时成为窗口..?
      猜你喜欢
      • 1970-01-01
      • 2015-06-24
      • 2015-01-24
      • 2015-02-26
      • 1970-01-01
      • 1970-01-01
      • 2015-01-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多