【问题标题】:An interval that calls a function inside an object, which also calls a function inside that object调用对象内部函数的区间,该函数也调用该对象内部的函数
【发布时间】:2012-05-23 15:45:44
【问题描述】:
function airEngineJS (canvasArg, properties) {

    this.canvas = (canvasArg == "undefined")? trace("Failed to set up canvas for airEngineJS") : canvasArg;
    this.cameras = [];
    this.displayObjects = [];
    this.hudDisplayObjects = [];
    this.fps = (properties == "undefined" || properties.fps == "undefined")? 30 : properties.fps;

    if (properties == "undefined" || properties.autoinit == "undefined" || properties.autoinit == true){
      this.keyboard = new keyboardJS();
      this.keyboard.init();
      this.cameras.push(new airCameraJS(this));
    }
    this.enterframe = setInterval(this.intervalCaller, 1000/this.fps);
    trace("A new airEngineJS has been created");
  }
  airEngineJS.prototype = {
    intervalCaller : function () {
      this.mainLoop();
    },
    logic : function () {
      for (var i = 0; i < this.displayObjects.length; ++i){
        this.displayObjects[i].logic();
      }
      for (var j = 0; j < this.cameras.length; ++j){
        this.cameras[j].logic();
      }
    },
    render : function () {
      for (var i = 0; i < this.cameras.length; ++i){
        for (var j = 0; j < this.displayObjects.length; ++j){
          this.displayObjects[j].renderOn(this.cameras[i]);
        }
      }
      for (var i = 0; i < this.hudDisplayObjects.length; ++i){
        this.hudDisplayObjects[i].renderOn(this.canvas);
      }
    },
    mainLoop : function () {
      this.logic();
      this.render();
    }
  }

区间 [this.enterframe = setInterval(this.intervalCaller, 1000/this.fps);] 调用正确 (this.intervalCaller),但是 this 尝试在 DOM 中调用 (this.mainLoop())。

关于我应该如何做的任何建议? :(

【问题讨论】:

    标签: javascript function scope this setinterval


    【解决方案1】:

    您可以像这样关闭实际的函数调用:

    var self = this;
    this.enterframe = setInterval(function() {
        self.intervalCaller();
    }, 1000/this.fps);
    

    它首先创建一个对新实例的引用,然后在传递给setInterval的闭包中使用它。

    【讨论】:

    • 我的代码有问题,它停止工作了...我正在尝试解决它,我会告诉你是否有效...
    • @DavidDaSilvaContín 如果您想验证代码,可以查看此小提琴:jsfiddle.net/qetAK
    • 我已经成功了!这是一个奇怪的问题。我相信它只是通过在“未定义”比较中将 更改为 来工作。无论如何我都会检查链接:) 代码运行良好。谢谢!我相信我现在明白了:/ 所以,它正在尝试在 DOM 中执行,因为路径/路由正在使用“this”,并且它不再在对象内部,或多或少?:|
    • 哦,小提琴是显示代码工作的示例。不错:)
    • @DavidDaSilvaContín 是的,setInterval 将调用该函数,但会将this 绑定到window;关闭阻止了
    猜你喜欢
    • 1970-01-01
    • 2010-10-27
    • 1970-01-01
    • 2021-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-19
    相关资源
    最近更新 更多