0

问题出在游戏的 rects 实例上:[],它应该是 Rect 对象数组。当我访问 Game 中的 rects 属性时,会给出未定义的结果。

http://jsbin.com/ibilec/34/edit

(function(window, document, console) {
  'use strict';

  function Rect() {
    this.x = 0;
    this.y = 0;
    this.width = 20;
    this.height = 20;
  }

  Rect.prototype.draw = function(ctx) {
    ctx.fillRect(this.x, this.y, this.width, this.height);
  };


  var Game = Object.create({    
    rects: [],  /// PROBLEM IS WITH this

    draw: function() {
      console.log('Draw called', this.rects);
      if (this.rects) {
        this.rects.forEach(function(rect, index) {
          console.log(rect);
          rect.draw(this.ctx);
        });
      }

      //window.setInterval(function() { this.ctx.clearRect(0, 0, 200, 200); }, 1000);


    },

    genRect: function() {
      var newRect = new Rect();
      newRect.x = parseInt(Math.random() * 200, 10);
      newRect.y = parseInt(Math.random() * 200, 10);

      this.rects.push(newRect);
    },

    loop: function() {
      //Game.draw();
      // Frame rate about 30 FPS

      window.setInterval(this.draw, 1000 / 30);
    },

    init: function() {
      this.canvas = document.getElementById('game'); 
      this.height = this.canvas.height;
      this.width = this.canvas.width;

      window.ctx = this.canvas.getContext('2d');


      this.genRect();
      this.loop(); //start loop
    }
  });

  var game = Object.create(Game);
  game.init();
})(window, document, console);
4

1 回答 1

2

draw方法不是作为对象的方法调用的,而是作为全局范围内的函数调用的,因此this将是对 的引用window,而不是对 Game 对象的引用。

复制this到一个变量,并使用它从函数中调用方法:

var t = this;
window.setInterval(function() { t.draw(); }, 1000 / 30);
于 2013-01-13T12:57:31.977 回答