调用对象内部函数的间隔,也调用该对象内的函数

时间:2012-05-23 15:45:44

标签: javascript function scope this setinterval

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();
    }
  }

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

有关我应该怎么做的任何建议? :(

1 个答案:

答案 0 :(得分:1)

您可以关闭实际的函数调用,如下所示:

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

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

相关问题