在setInterval中找不到函数

时间:2015-12-22 10:08:19

标签: javascript

我是javascript的新手(第三天!)但我很长一段时间都是程序员。使用javascript的setInterval函数时出现以下问题:

<script>
  var canvasObj, canvasContext;
  var tetrisObj;

  main();

  function main() {
    log("call init");
    init();
    tetrisObj.startGame(canvasContext)
    log("finished");
  }

  function init() {
    canvasObj = document.getElementById("Tetris");
    canvasContext = canvasObj.getContext("2d");
    tetrisObj = new tetris(canvasObj.width, canvasObj.height);
  }

  function log(string) {
    var p = document.createElement("p");
    var text = document.createTextNode(string);
    p.appendChild(text);
    document.getElementById("logs").appendChild(p);
  }

  function tetris(width, height) {
    this.width = width;
    this.height = height;

    this.b_width = width * 0.1;
    this.b_height = width * 0.1;

    this.block_container = new Array();

    this.tetris_context;

    this.startGame = function(canvasContext) {
      this.tetris_context = canvasContext;
      this.addBlock();
      this.gameLoop();
      setInterval(this.gameLoop, 500);
    }

    this.gameLoop = function() {
      this.updateBlocks();
      this.drawBlocks();
    }

    this.updateBlocks = function() {
      var i = 0;
      log(this.block_container.length);
      for (i = 0; i < this.block_container.length; i++) {
        if (this.block_container[i].y >= 20 * this.b_height) {
          continue;
        } else {
          this.block_container[i].y += this.b_height;
          log(this.block_container[i].y);
        }
      }
    }

    this.addBlock = function() {
      var new_block = new s_block(0, 0, "black", this.b_width, this.b_height);
      this.block_container.push(new_block);
    }

    this.drawBlocks = function() {
      var i = 0;
      for (i = 0; i < this.block_container.length; i++) {
        this.block_container[i].drawBlock(this.tetris_context);
      }
    }

  }

  function s_block(x, y, color, width, height) {
    this.x = x;
    this.y = y;
    this.color = color;
    this.width = width;
    this.height = height;

    this.drawBlock = function(context) {
      context.save();
      context.fillStyle = color;
      context.fillRect(this.x, this.y, this.width, this.height);
      context.restore();
    }

  }
</script>

我遇到的问题是,当运行上面代码片段的“startGame()”函数时,会找到对this.gameLoop的直接调用,但是通过setInterval对this.gameLoop的间接调用失败。我认为这可能是因为它在全局上下文中执行,这与“this”对象混淆。但是我不太明白如何优雅地解决它!

0 个答案:

没有答案
相关问题