繁体   English   中英

window.setInterval 使用本地 function

[英]window.setInterval using local function

我正在使用window.setInterval ,它必须能够访问在“类”中定义的方法,但是由于setInterval位于 scope 中,与定义它的方法分开, this解析为window而不是所需的Game实例。 我可以使用什么代码来获得调用Game.update而不是window.update的所需行为?

(这看起来有点令人困惑。也许以下不正确的代码可以使事情变得清晰一些。)

game = function () {
    /* ... */
    this.update = function () {
        /* ... */
    }
    this.interval = window.setInterval(this.update /* !!! */, 50);
}

这可以在没有JS框架的情况下完成。

var game = function() {
  this.update = function() { }
  var that = this;
  setInterval(function() {
    that.update.apply(that);
  },50);
}

问题出在this关键字上。 它在setInterval中不可用。 下面的代码应该可以工作。

game = function () {
    /* ... */
    this.update = function () {
        /* ... */
    var that = this  // add this line and use that instead of this in setInterval function
    }
    this.interval = window.setInterval(that.update /* !!! */, 50);
}

您需要将方法绑定到对象。

有关使用示例,请参阅https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind ,以及为旧浏览器提供bind()支持的插件脚本。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM